- Trending Categories
- Data Structure
- Operating System
- C Programming
- 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.
# without using bigInteger def calculateSum() sumOfNumbers = 0 10_000.times do sumOfNumbers = sumOfNumbers + 0.0001 end return sumOfNumbers end puts calculateSum()
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.
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()
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")
- 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