为什么我得到不同的 BigDecimal 舍入结果?
Why I'm getting different BigDecimal rounding results?
为什么我得到以下输出:
1.11
1.13
当 运行 下面的代码:
public static void main(String[] args) {
double aDouble = 1.115;
double bDouble = 1.125;
System.out.println(roundTo2Decimal(aDouble));
System.out.println(roundTo2Decimal(bDouble));
}
public static BigDecimal roundTo2Decimal(double doubleToRound){
BigDecimal bigDecimal = new BigDecimal(doubleToRound);
return bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP);
}
而不是预期结果:
1.12
1.13 ?
很确定这只是标准的浮点不精确。 0.125 = 1/8 这完全可以用二进制表示。 0.115 不是,所以它没有准确存储,而且显然存储为与您期望的四舍五入的东西。尝试 System.out.println
替身本身。
这是由于将 1.115 表示为双精度时的精度损失:
1.115 = 1.114999999999999991118215803E0
1.125 = 1.125E0
<code>
//to achieve what u need change your method to
public static BigDecimal roundTo2Decimal(double doubleToRound) {
BigDecimal bigDecimal = new BigDecimal(doubleToRound);
return bigDecimal.setScale(2, RoundingMode.CEILING);
}
</code>
为什么我得到以下输出:
1.11
1.13
当 运行 下面的代码:
public static void main(String[] args) {
double aDouble = 1.115;
double bDouble = 1.125;
System.out.println(roundTo2Decimal(aDouble));
System.out.println(roundTo2Decimal(bDouble));
}
public static BigDecimal roundTo2Decimal(double doubleToRound){
BigDecimal bigDecimal = new BigDecimal(doubleToRound);
return bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP);
}
而不是预期结果:
1.12
1.13 ?
很确定这只是标准的浮点不精确。 0.125 = 1/8 这完全可以用二进制表示。 0.115 不是,所以它没有准确存储,而且显然存储为与您期望的四舍五入的东西。尝试 System.out.println
替身本身。
这是由于将 1.115 表示为双精度时的精度损失:
1.115 = 1.114999999999999991118215803E0
1.125 = 1.125E0
<code>
//to achieve what u need change your method to
public static BigDecimal roundTo2Decimal(double doubleToRound) {
BigDecimal bigDecimal = new BigDecimal(doubleToRound);
return bigDecimal.setScale(2, RoundingMode.CEILING);
}
</code>