In the early hours of this morning, I was creating reports that required a high degree of accuracy. For data processing, I rely on BigQuery, and for display, I rely on Data Studio. After putting in a few hours of effort and feeling a sense of accomplishment, I noticed that my data had several big discrepancies.
As far as my data analysis algorithm was concerned, I was confident in its correctness. Instead, I understood the fault was with the way in which the data was generated, not the data itself.
After auditing my code on how data was being generated, I realized I was using floating points for monetary values. The problem was not on using the floating points themselves, but rather with how I was rounding up my numbers, which resulted in a 0.7 cents per transaction mistake.
While BigDecimal has the ability to hold more accuracy than double, it is rarely necessary. The main reason for its employment is that it clarifies how rounding is done, including a variety of rounding techniques. In most situations, you can get the same results with double, but unless you know the procedures, BigDecimal is the way to go in these cases.
Using BigDecimal
public static String CurrencyFormat(double value) {
NumberFormat format = NumberFormat.getCurrencyInstance(new Locale("en", "KE"));
format.setMinimumFractionDigits(2);
format.setMaximumFractionDigits(5);
format.setRoundingMode(RoundingMode.HALF_EVEN);
return format.format(value);
}
I wrote the code above for two reasons
RoundingMode.HALF_EVEN
This method rounds the ideal (infinitely precise) result of an arithmetic operation to the nearest representable value and gives that representation as the result. In the case of a tie, the value that would make the significand end in an even digit is chosen.
Precision and Scale
Precision is the total number of digits (or significant digits) of a real number.
Scale specifies the number of digits after the decimal place. For example, 12.345 has a precision of 5 (total digits) and a scale of 3 (number of digits right of the decimal).
The fatal effects of misusing precision
On February 25, 1991, a loss of significance in a MIM-104 Patriot missile battery prevented it from intercepting an incoming Scud missile in Dhahran, Saudi Arabia, contributing to the death of 28 soldiers from the U.S. Army’s 14th Quartermaster Detachment.






0 Comments