How To Calculate Exact Values In Java Using Double Vs BigDecimal
Here
is an example to use double to represent the values in Java.
public
class
ProblemWithDouble {
public
static
void
main(String[] args)
{
System.out.println("---
Normal Print-----");
System.out.println(2.00
- 1.1);
System.out.println(2.00
- 1.2);
System.out.println(2.00
- 1.3);
System.out.println(2.00
- 1.4);
System.out.println(2.00
- 1.5);
System.out.println(2.00
- 1.6);
System.out.println(2.00
- 1.7);
System.out.println(2.00
- 1.8);
System.out.println(2.00
- 1.9);
System.out.println(2.00
- 2);
}
}
output:
---
Normal Print-----
0.8999999999999999
0.8
0.7
0.6000000000000001
0.5
0.3999999999999999
0.30000000000000004
0.19999999999999996
0.10000000000000009
0.0
In
the output, it cannot calculate all double decimals precisely.
Solution:
using BigDecimal
import
java.math.BigDecimal;
public
class
ProblemWithDouble {
public
static
void
main(String[] args)
{
System.out.println("---
BigDecimal-----");
System.out.println(new
BigDecimal("2.00").subtract(new
BigDecimal("1.1")));
System.out.println(new
BigDecimal("2.00").subtract(new
BigDecimal("1.2")));
System.out.println(new
BigDecimal("2.00").subtract(new
BigDecimal("1.3")));
System.out.println(new
BigDecimal("2.00").subtract(new
BigDecimal("1.4")));
System.out.println(new
BigDecimal("2.00").subtract(new
BigDecimal("1.5")));
System.out.println(new
BigDecimal("2.00").subtract(new
BigDecimal("1.6")));
System.out.println(new
BigDecimal("2.00").subtract(new
BigDecimal("1.7")));
System.out.println(new
BigDecimal("2.00").subtract(new
BigDecimal("1.8")));
System.out.println(new
BigDecimal("2.00").subtract(new
BigDecimal("1.9")));
System.out.println(new
BigDecimal("2.00").subtract(new
BigDecimal("2")));
}
}
output:
---
BigDecimal-----
0.90
0.80
0.70
0.60
0.50
0.40
0.30
0.20
0.10
0.00
BigDecimal
performs exact decimal arithmetic.
Conclusion
In
Java, it’s
recommended to use BigDecimal to represent the monetary calculations.
However BigDecimal calculations are slower than those with primitive
data type calculations, which may be an issue for heavy decimal
calculations program, but there’s should be no problem for most
programs.
0 comments:
Post a Comment