【问题标题】:How to round a very small floating point number with trailing zeros?如何用尾随零舍入一个非常小的浮点数?
【发布时间】:2020-04-02 23:25:46
【问题描述】:

目前我的代码呈现数字:

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"

【问题讨论】:

  • 有什么要求? A) 总是在小数点后显示 N 个数字,或 B) 总是显示 N 个小数点后大于 0 的数字?
  • @Casper 我已经编辑了我的 OP 以回应您的问题。为了清楚起见:我想要 A) 总是在小数点后显示 N 位数。

标签: ruby floating-point numbers rounding


【解决方案1】:

您可以设置显示的位数:

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

【讨论】:

    【解决方案2】:

    您可以定义一个新方法来做到这一点。 我使用 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"
    

    【讨论】:

      猜你喜欢
      • 2015-02-16
      • 1970-01-01
      • 2023-03-05
      • 2021-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多