如何在 Ruby 中使用 BigDecimal?


使用BigDecimal,你可以执行任意精度的浮点数十进制运算。让我们用一个示例来理解BigDecimal 的用例。我们将举两个示例,第一个示例将不使用BigDecimal,第二个示例中,我们将会使用BigDecimal

考虑下面显示的代码,我们在其中不使用BigDecimal,并多次向一个数字中添加一些十进制值。

示例 1

Open Compiler
# without using bigInteger def calculateSum() sumOfNumbers = 0 10_000.times do sumOfNumbers = sumOfNumbers + 0.0001 end return sumOfNumbers end puts calculateSum()

输出

0.9999999999999062

现在,让我们对上面显示的示例使用BigDecimal,看看它会产生什么差异。

考虑下面显示的代码,其中使用了BigDecimal

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

示例 2

Open Compiler
require 'bigdecimal' # with using bigInteger def calculateSum() sumOfNumbers = BigDecimal("0") 10_000.times do sumOfNumbers = sumOfNumbers + BigDecimal("0.0001") end return sumOfNumbers end puts calculateSum()

输出

0.1e1

示例 3

BigDecimal 有时在除零时需返回无穷大。考虑下面显示的代码。

Open Compiler
require 'bigdecimal' puts BigDecimal("2.0") / BigDecimal("0.0") puts BigDecimal("-2.0") / BigDecimal("0.0")

输出

Infinity
-Infinity

更新于: 2022 年 1 月 25 日

1K+ 浏览

开启你的职业

完成课程获得认证

开始
广告