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