public static double centsToDollars(Number cents, int precision) {
return BigDecimal.valueOf(cents.doubleValue() / 100).setScale(precision, RoundingMode.DOWN).doubleValue();
}
Code above works completely fine when I want to display cents value in dollars. For example, for 1 cent, it returns 0.01 dollar.
assertEquals("$0.01", FormatUtils.centsToDollars(1, 3))
assertEquals("$0.012", FormatUtils.centsToDollars(1.2345, 3))
assertEquals("$0.327", FormatUtils.centsToDollars(32.7, 3))
But I can’t figure out, why FormatUtils.centsToDollars(0.65, 3) returns $0.0060. I expect to receive 0.006 instead. What is the latest zero about ?
Update
Looks like the root cause of the issue is invocation of doubleValue() of BigDecimal
System.out.println(Double.parseDouble("0.006"));
System.out.println(BigDecimal.valueOf(0.006).doubleValue());
returns 0.0060 for me
Any clue why this happens ?
There is a bug id:4428022 in Java 1.4 to 6 which means it adds an extra zero you don’t need. This happens for values 0.001 to 0.009 only. Java 7 doesn’t have this bug.
in Java 6 prints
0.0010
0.0020
0.0030
0.0040
0.0050
0.0060
0.0070
0.0080
0.0090
but in Java 7 prints
0.001
0.002
0.003
0.004
0.005
0.006
0.007
0.008
0.009
I suspect that 0.65 is actually slightly less in reality. When you divide it by 100 you get something like 0.006499999999999 which when rounded drops to 0.006
I suspect what you wanted was
Try
This is how I would write it
This assumes two decimal places of cents.