How to use BigDecimal in Ruby?

RubyServer Side ProgrammingProgramming

Using BigDecimal, you can perform floating point decimal arithmetic with arbitrary precision. Let's try to understand the BigDecimal usecase with the help of an example. We will take two examples, where the first one will make use of no BigDecimal and in the second example, we will use BigDecimal.

Consider the code shown below, where we aren't making use of BigDecimal and adding some decimal values multiple times to a number.

Example 1

# without using bigInteger

def calculateSum()
   sumOfNumbers = 0
   10_000.times do
      sumOfNumbers = sumOfNumbers + 0.0001
   end
   return sumOfNumbers
end

puts calculateSum()

Output

0.9999999999999062

Now, let's use BigDecimal on the same example shown above and see what difference it makes.

Consider the code shown below where BigDecimal is used.

Example 2

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()

Output

0.1e1

Example 3

When dividing a value by zero, BigDecimal sometimes needs to return infinity. Consider the code shown below.

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

Output

Infinity
-Infinity
raja
Updated on 25-Jan-2022 11:15:52

Advertisements