Printing to specific (runtime-determined) precision in Julia

◇◆丶佛笑我妖孽 提交于 2020-01-03 19:18:26

问题


Given a value x and an integer n (assigned at runtime), I want to print x to exactly n digits after the decimal (after rounding if needed).

print(round(x, n)) works fine for (x,n)=(3.141592, 3) but for (x,n)=(2.5,5), it prints just 2.5, not 2.50000 (5 digits after decimal point).

If I knew n at runtime, say 5, I could do

@printf("%.5f", x)

But @printf being a macro needs n to be known at compile time.

Is this possible using some show magic or something else?


回答1:


Using the fresh new Format.jl package:

using Format

function foo(x, n)
    f = FormatSpec(".$(n)f")
    pyfmt(f, x)
end

foo(2.5, 5)



回答2:


Unfortunately, for some reason the julia version of @printf / @sprintf do not support the "width" sub-specifier as per the c printf standard (see man 3 printf).

If you're feeling brave, you can rely on the c sprintf which supports the "dynamic width" modifier, to collect a string that you then just print as normal.

A = Vector{UInt8}(100); # initialise array of 100 "chars"
ccall( :sprintf, Int32, (Ptr{UInt8}, Cstring, Int64, Float64), A, "%.*f", 4, 0.1 )
print( unsafe_string(pointer(A)) )    #> 0.1000

Note the asterisk in %.*f, and the extra input 4 serving as the dynamic width modifier.



来源:https://stackoverflow.com/questions/50743164/printing-to-specific-runtime-determined-precision-in-julia

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!