Consider this:
double first = 2.00;
double second = 1.10;
System.out.println(first - second);The result?
0.8999999999999999The problem comes when double suffers from a "loss of precision" and becomes very noticeable when working with either very big numbers or very small numbers. You may be tempted to use print formatting to set the precision in terms of decimal placings, but that still do not solve the root issue.
Especially for monetary-critical applications, (i) you may want to consider using BigDecimal as it is an exact way of representing numbers. With BigDecimal this would not happen. (ii) use int or long to represent cents.
1. Using BigDecimal
Example
BigDecimal first = new BigDecimal("2.00");
BigDecimal second = new BigDecimal("1.10");
System.out.println(first.subtract(second));Returns
0.90
When using BigDecimal, note that it'll take up more memory, creates more garbage and is probably slower for most operations, as compared to using primitive types.
2. Using int or long
Example
2. Using int or long
Example
System.out.println((200 - 110) + " cents");Returns
90 centsIn summary, avoid floating point calculations (e.g. float, double) when working with monetary or precision-critical applications. Consider greatly the use of int, long or BigDecimal instead.
No comments:
Post a Comment