Float.parseFloat() is the problem as it returns a new float
.
Returns a new float initialized to the value represented by the specified String, as performed by the valueOf method of class Float.
You are formatting just for the purpose of display . It doesn't mean the float
will be represented by the same format internally .
You can use java.lang.BigDecimal.
I am not sure why are you using parseFloat()
twice. If you want to display the float
in a certain format then just format it and display it.
Float litersOfPetrol=Float.parseFloat(stringLitersOfPetrol);
DecimalFormat df = new DecimalFormat("0.00");
df.setMaximumFractionDigits(2);
System.out.println("liters of petrol before putting in editor"+df.format(litersOfPetrol));