在Ruby中设置浮点的显示精度 [英] Set the display precision of a float in Ruby

查看:206
本文介绍了在Ruby中设置浮点的显示精度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



类似于:

<$ p

是否可以在Ruby中设置float的显示精度? $ p> 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。


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?

解决方案

z.round(2) or x.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.

这篇关于在Ruby中设置浮点的显示精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆