在Ruby中设置float的显示精度

sal*_*cer 55 ruby floating-point precision

是否可以在Ruby中设置float的显示精度?

就像是:

z = 1/3
z.to_s    #=> 0.33333333333333
z.to_s(3) #=> 0.333
z.to_s(5) #=> 0.33333
Run Code Online (Sandbox Code Playgroud)

或者我必须覆盖to_s方法Float

Dre*_*ewB 81

z.round(2)或者x.round(3)是最简单的解决方案.见http://www.ruby-doc.org/core-1.9.3/Float.html#method-i-round.

也就是说,这只会确保它不会超过那么多位数.在1/3的情况下,这很好,但如果你说0.25.round(3)你会得到0.25,而不是0.250.


Tho*_*ini 43

你可以使用sprintf:

sprintf( "%0.02f", 123.4564564)
Run Code Online (Sandbox Code Playgroud)

  • 这有点有趣,我从未在生活中使用过红宝石.我不知道如何写一个你好世界的节目,从来没有.我可能只是搜索了OP的问题并发布了答案. (10认同)
  • 我更喜欢这种情况,因为我想要'.(圆)(2)`不给出的".00". (5认同)

Dig*_*oss 35

我通常只是在开放代码中进行转换,例如:

puts "%5.2f" % [1.0/3.0] 
Run Code Online (Sandbox Code Playgroud)

Ruby 为这样的表达式调用Kernel#format,因为String上有一个核心运算符%.如果它为你敲响任何铃声,可以把它想象成Ruby的printf.

  • 有谁能解释一下? (8认同)

Har*_*rel 6

Rubocop 建议使用#formatover#sprintf和 using 带注释的字符串标记。

的语法#format

%[flags][width][.precision]type
Run Code Online (Sandbox Code Playgroud)

例子:

# Ensure we store z as a float by making one of the numbers a float.
z = 1/3.0

# Format the float to a precision of three.
format('%<num>0.3f', num: z)
# => "0.333"

format('%<num>0.5f', num: z)
# => "0.33333"

# Add some text to the formatted string
format('I have $%<num>0.2f in my bank account.', num: z)
# => "I have $0.33 in my bank account."
Run Code Online (Sandbox Code Playgroud)

参考: