如何用尾随零舍入一个非常小的浮点数?
How to round a very small floating point number with trailing zeros?
目前我的代码呈现数字:
x = 0.000092627861766
p x
类似于 BigInt 格式,这样:
=> 9.0e-05
有没有一种方法可以调用变量 return 一个四舍五入的浮点数(数字或字符串格式),这样:
x.some_method
# Always show N number of digits after the initial decimal point.
=> 0.00009263
OR
=> "0.00009263"
您可以设置要显示的位数:
p "%0.08f" % x # => "0.00009263"
您可以定义一个新方法来执行此操作。
我使用 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"
目前我的代码呈现数字:
x = 0.000092627861766
p x
类似于 BigInt 格式,这样:
=> 9.0e-05
有没有一种方法可以调用变量 return 一个四舍五入的浮点数(数字或字符串格式),这样:
x.some_method
# Always show N number of digits after the initial decimal point.
=> 0.00009263
OR
=> "0.00009263"
您可以设置要显示的位数:
p "%0.08f" % x # => "0.00009263"
您可以定义一个新方法来执行此操作。 我使用 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"