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:
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
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.