如何将一个非常小的浮点数四舍五入为零?

时间:2020-04-02 23:25:46

标签: ruby floating-point numbers rounding

当前,我的代码呈现了数字:

x = 0.000092627861766
p x

类似于BigInt格式,例如:

=> 9.0e-05 

有没有一种我可以在变量上调用的方法来返回舍入的浮点数(数字或字符串格式),使得:

x.some_method
# Always show N number of digits after the initial decimal point.
=> 0.00009263 
OR 
=> "0.00009263"

2 个答案:

答案 0 :(得分:5)

您可以设置要显示的位数:

p "%0.08f" % x # => "0.00009263"

答案 1 :(得分:1)

您可以定义一个新方法来执行此操作。 我使用BigDecimal只是为了提高准确性并防止出现意外结果, 但我认为您可以在Float中执行相同的操作:

require 'bigdecimal'
class BigDecimal
  def round_after_n(n)
    round(self.exponent.abs + n + 1)
  end
end
x = BigDecimal('0.000092627861766')
#  => 0.926279e-4 
x.round_after_n(5).to_s('F')
#  => "0.0000926279"