
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Use BigDecimal in Ruby
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
Advertisements