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)
Dig*_*oss 35
我通常只是在开放代码中进行转换,例如:
puts "%5.2f" % [1.0/3.0]
Run Code Online (Sandbox Code Playgroud)
Ruby 为这样的表达式调用Kernel#format,因为String上有一个核心运算符%.如果它为你敲响任何铃声,可以把它想象成Ruby的printf.
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)
参考: