@printf: significant digits in floating point representation

hi i want tu use @sprintf to format a number to floating point representation with a fixed amount of significant digits
how can I do that?
The function shout act the following way:

.000012340000 -> 0.000012
.123400000000 -> 0.12
1.234 -> 1.2
1234000.000 -> 1200000

best…

edit: misread your question, you want significant digits not decimal digits

I think %.3e or %.3g may be what you’re looking for, which gives scientific notation

…but the problem is, that i want to use this to throw the number against Tikz / PGFplotsX. but LaTeX can not deal with scientific notation very well.

as a last resort, you can always get the string and manipulate that

edit: actually, should have looked at round first
https://github.com/JuliaLang/julia/issues/21101#issuecomment-446958508

julia> round(pi, digits=3)
3.142

julia> round(pi, sigdigits=3)
3.14
1 Like

Hahaha…. yes this i also had i mind but and the thread ended up in this issue

but now:

julia> round(.000012340000, sigdigits=3)
1.23e-5
julia> @printf "%.f" round(.000012340000, sigdigits=3)
0.000012

well this is slightly wrong too…um, yea just be a string wrangler for now I guess, sorry bud

2 Likes

I feared that answer :cry:
thanks for now… still hoping for a better solution…

1 Like

Fyi, you might want to check out this MATLAB solution.

Below is a simplified Julia version that produces the desired output:

using Printf

function str_significant(x::Float64, sigdig::Int)
    (x == 0) && (return "0")
    x = round(x, sigdigits=sigdig)
    n = length(@sprintf("%d", abs(x)))              # length of the integer part
    if (x ≤ -1 || x ≥ 1)
        decimals = max(sigdig - n, 0)               # 'sig - n' decimals needed 
    else
        Nzeros = ceil(Int, -log10(abs(x))) - 1      # No. zeros after decimal point before first number
        decimals = sigdig + Nzeros
    end 
    return @sprintf("%.*f", decimals, x)
end

str_significant(.000012340000, 2)                   # 0.000012
str_significant(.123400000000, 2)                   # 0.12
str_significant(1.234, 2)                           # 1.2
str_significant(1234000.000, 2)                     # 1200000

Can’t you use a simple regex to change e+XXX to \times {10}^{XXX} for LaTeX?

Is there a reason that you can’t use siunitx, the LateX package that is designed for this? In my code to automatically generate tables, I have lots of @printf "\\num{%4.3e} \\n and so on.

2 Likes

Nice, thanks
this problem however is that old, that I can’t remember the final use case anymore. :woozy_face: (and the GitHub issue is still open :slight_smile:

1 Like

I’m quite sure there was a reason I forgot about… sorry :roll_eyes: