使用Julia打印到特定的(运行时确定的)精度 [英] Printing to specific (runtime-determined) precision in Julia
本文介绍了使用Julia打印到特定的(运行时确定的)精度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给出一个值x和一个整数n(在运行时分配),我想将x打印到精确到小数点后的n位(如果需要的话,四舍五入)。
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))
对于(x,n )=(3.141592,3)
,但对于(x,n)=(2.5,5)
,它仅打印 2.5
,而不是 2.50000
(小数点后5位)。
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).
如果我在运行时知道n,说5,我可以做
If I knew n at runtime, say 5, I could do
@printf("%.5f", x)
但是@printf是宏需要n在编译时知道。
But @printf being a macro needs n to be known at compile time.
是否可以使用某些演出
魔术或其他方式?
Is this possible using some show
magic or something else?
推荐答案
使用全新的 Format.jl 包:
using Format
function foo(x, n)
f = FormatSpec(".$(n)f")
pyfmt(f, x)
end
foo(2.5, 5)
这篇关于使用Julia打印到特定的(运行时确定的)精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文