How to round a float value [closed]

帅比萌擦擦* 提交于 2019-12-13 09:08:41

问题


I'm trying to round a float value as follows:

(0.11 + 0.22 + 0.23 / 3).round(2)

Does anyone know if there is other effective way to round up?


回答1:


If you always want to round up and never down, you can do this:

(0.411 * 100).ceil / 100.0 # => 0.42

Otherwise just use round. Or use the string formatter if you don't mind your float turning into a string.




回答2:


The main ways to round a floating point number in Ruby are via the Float#round method or the String#% (format) operator. For example:

f = (0.11 + 0.22 + 0.23 / 3) # => 0.4066666666666667
f.round(2)  # =>  0.41
"%.02f" % f # => "0.41"


来源:https://stackoverflow.com/questions/13716057/how-to-round-a-float-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!