是否可以在 Ruby 中设置浮点数的显示精度?
就像是:
z = 1/3
z.to_s #=> 0.33333333333333
z.to_s(3) #=> 0.333
z.to_s(5) #=> 0.33333
还是我必须重写的to_s
方法Float
?
是否可以在 Ruby 中设置浮点数的显示精度?
就像是:
z = 1/3
z.to_s #=> 0.33333333333333
z.to_s(3) #=> 0.333
z.to_s(5) #=> 0.33333
还是我必须重写的to_s
方法Float
?
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。
您可以使用 sprintf:
sprintf("%0.02f", 123.4564564)
我通常会在开放代码中进行转换,例如:
puts "%5.2f" % [1.0/3.0]
Ruby 为这样的表达式调用Kernel#format,因为 String 上定义了一个核心运算符 %。如果这对您有任何影响,请将其视为Ruby 的 printf。
Rubocop 建议使用#format
over#sprintf
和使用带注释的字符串标记。
的语法#format
是
%[flags][width][.precision]type
例子:
# 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."
参考:
你可以使用看跌期权
z = #{'%.3f' % z}