这里是Java 8。根据Google的说法:
- 将英镑转换为千克:乘以0.453592
- 将千克转换为磅:乘以2.20462
- 将英寸转换为米:乘以0.0254
- 将米转换为英寸:乘以39.3701
我写了这段Java代码:
public class MeasurementConverter {
private static final int SCALE = 2;
public static void main(String[] args) {
new MeasurementConverter().run();
}
private void run() {
BigDecimal hundredLbs = new BigDecimal(100.00);
BigDecimal hundredInches = new BigDecimal(100.00);
System.out.println(hundredLbs + " pounds is " + poundsToKilos(hundredLbs) + " kilos and converts back to " + kilosToPounds(poundsToKilos(hundredLbs)) + " pounds.");
System.out.println(hundredInches + " inches is " + inchesToMeters(hundredInches) + " meters and converts back to " + metersToInches(inchesToMeters(hundredInches)) + " inches.");
}
private BigDecimal metersToInches(BigDecimal meters) {
return meters.multiply(new BigDecimal("39.3701").setScale(SCALE, BigDecimal.ROUND_HALF_UP));
}
private BigDecimal inchesToMeters(BigDecimal inches) {
return inches.multiply(new BigDecimal("0.0254").setScale(SCALE, BigDecimal.ROUND_HALF_UP));
}
private BigDecimal kilosToPounds(BigDecimal kilos) {
return kilos.multiply(new BigDecimal("2.20462").setScale(SCALE, BigDecimal.ROUND_HALF_UP));
}
private BigDecimal poundsToKilos(BigDecimal pounds) {
return pounds.multiply(new BigDecimal("0.45359").setScale(SCALE, BigDecimal.ROUND_HALF_UP));
}
}
当运行时,它会打印出以下内容:
100 pounds is 45.00 kilos and converts back to 99.0000 pounds.
100 inches is 3.00 meters and converts back to 118.1100 inches.
我原本期望它会输出:
100.00 pounds is 45.00 kilos and converts back to 100.00 pounds.
100.00 inches is 3.00 meters and converts back to 100.00 inches.
我只关心英制与公制的转换精确到小数点后两位,并且最终输出结果始终精确到小数点后两位。有人能看出我的问题在哪里,以及应该如何修复吗?
double
传递给new BigDecimal
会丢失精度,因为您没有使用确切的值,而是使用最接近的可表示值作为双精度浮点数。请改用new BigDecimal("39.37")
等。还要记住,这些倒数不是精确的,因此39.37 * 0.0254 = 0.999998,而不是1。 - Andy Turner