public static double centsToDollars(Number cents, int precision) {
return BigDecimal.valueOf(cents.doubleValue() / 100).setScale(precision, RoundingMode.DOWN).doubleValue();
}
当我想以美元显示美分值时,上面的代码完全可以正常工作。例如,对于 1 美分,它返回 0.01 美元。
assertEquals("$0.01", FormatUtils.centsToDollars(1, 3))
assertEquals("$0.012", FormatUtils.centsToDollars(1.2345, 3))
assertEquals("$0.327", FormatUtils.centsToDollars(32.7, 3))
但我想不通,为什么FormatUtils.centsToDollars(0.65, 3)
返回 0.0060 美元。我希望收到 0.006。最新的零是什么?
更新
看起来问题的根本原因是doubleValue()
调用BigDecimal
System.out.println(Double.parseDouble("0.006"));
System.out.println(BigDecimal.valueOf(0.006).doubleValue());
为我返回 0.0060
任何线索为什么会发生这种情况?