在 Ruby 中设置浮点数的显示精度
是否可以在 Ruby 中设置浮点数的显示精度?
比如:
z = 1/3
z.to_s #=> 0.33333333333333
z.to_s(3) #=> 0.333
z.to_s(5) #=> 0.33333
或者我是否必须重写Float
的to_s
方法?
Is it possible to set the display precision of a float in Ruby?
Something like:
z = 1/3
z.to_s #=> 0.33333333333333
z.to_s(3) #=> 0.333
z.to_s(5) #=> 0.33333
Or do I have to override the to_s
method of Float
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
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。z.round(2)
orx.round(3)
is the simplest solution. See http://www.ruby-doc.org/core-1.9.3/Float.html#method-i-round.That said, that will only ensure that it is no more than that many digits. In the case of 1/3 that is fine, but if you had say
0.25.round(3)
you will get 0.25, not 0.250.您可以使用 sprintf:
You can use
sprintf
:我通常只会在开放代码中进行转换,例如:
Ruby 调用 Kernel#format 对于这样的表达式,因为 String 有一个 核心操作符%定义就可以了。如果这对您有任何启发,请将其视为Ruby 的 printf。
I would normally just do the conversion in open code, something like:
Ruby calls Kernel#format for expressions like this, because String has a core operator % defined on it. Think of it as printf for Ruby if that rings any bells for you.
Rubocop 建议使用
#format
#sprintf
并使用带注释的字符串标记。#format
的语法示例:
参考文献:
Rubocop recommends using
#format
over#sprintf
and using annotated string tokens.The syntax for
#format
isExample:
References:
您可以使用看跌期权
You can use puts