如何在float中将浮点数舍入到指定的有效数字位数? [英] How do I round a float to a specified number of significant digits in Ruby?
本文介绍了如何在float中将浮点数舍入到指定的有效数字位数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果有相当于 R's signif
It would be nice to have an equivalent of R's signif function in Ruby.
例如:
For example:
>> (11.11).signif(1)
10
>> (22.22).signif(2)
22
>> (3.333).signif(2)
3.3
>> (4.4).signif(3)
4.4 # It's usually 4.40 but that's OK. R does not print the trailing 0's
# because it returns the float data type. For Ruby we want the same.
>> (5.55).signif(2)
5.6
推荐答案
有可能是更好的办法,但这似乎工作正常:
There is probably better way, but this seems to work fine:
class Float
def signif(signs)
Float("%.#{signs}g" % self)
end
end
(1.123).signif(2) # => 1.1
(11.23).signif(2) # => 11.0
(11.23).signif(1) # => 10.0
这篇关于如何在float中将浮点数舍入到指定的有效数字位数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文