Java 8 here. According to Google:
So I whipped up this little Java code:
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));
}
}
When it runs it prints out:
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.
Whereas I was expecting it to print out:
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.
All I care about is that Imperial<->Metric conversion is accurate up to 2 decimal places and that the final outputs are always accurate up to 2 decimal places. Can anyone see where I'm going awry and what the fix is?
You have the brackets messed up. Consider this:
kilos.multiply(new BigDecimal("2.20462").setScale(SCALE, BigDecimal.ROUND_HALF_UP));
Here you first set scale on 2.20462
which results in 2.20
and then multiply.
Now consider the reverse conversion:
pounds.multiply(new BigDecimal("0.45359").setScale(SCALE, BigDecimal.ROUND_HALF_UP));
Here you effectively multiply by 0.45
. And 2.2*0.45=0.99
which explains the result.
You have set scale on the result of the multiplication, not on the multiplicator. Basically the last bracket is on the wrong place. It should be something like:
pounds.multiply(new BigDecimal("0.45359")).setScale(SCALE, BigDecimal.ROUND_HALF_UP);
Here's the corrected code.