- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to 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
- Related Articles
- How to use global variables in Ruby?
- How to Use Instance Variables in Ruby
- How to use the "defined?" keyword in Ruby?
- How to use the "not" keyword in Ruby?
- How to use the "or" keyword in Ruby?
- How to use the 'and' keyword in Ruby?
- Multiply one BigDecimal to another BigDecimal in Java
- How do I use Selenium with Ruby?
- Java Program to divide one BigDecimal from another BigDecimal
- Subtract one BigDecimal from another BigDecimal in Java
- How to use the 'break' and 'next' statements in Ruby?
- How to freeze objects in Ruby?
- How to Handle Exceptions in Ruby
- How to invoke methods in Ruby?
- How to Implement Multithreading in Ruby

Advertisements