I would like to convert an Double to an Float with two decimal places.
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
class Scratch {
private static final DecimalFormat df = new DecimalFormat("0.00");
public static void main(String[] args) {
Double worksAsIWouldExpect = 262143.05;
Double worksNotAsIWouldExpect = 262144.05;
convertAndPrint(worksAsIWouldExpect);
//DecimalFormat: 262143.05
//Big Decimal: 262143.05
convertAndPrint(worksNotAsIWouldExpect);
//DecimalFormat: 262144.06
//Big Decimal: 262144.06
}
public static void convertAndPrint(Double doubleValue) {
//DecimalFormat
String stringValueDf = df.format(doubleValue);
float floatValue = Float.parseFloat(stringValueDf);
System.out.println("DecimalFormat: " + floatValue);
//Big Decimal
BigDecimal decimalValue = new BigDecimal(doubleValue.toString());
decimalValue = decimalValue.setScale(2, RoundingMode.HALF_DOWN);
floatValue = decimalValue.floatValue();
System.out.println("Big Decimal: " + floatValue);
}
}
Output:
DecimalFormat: 262143.05
Big Decimal: 262143.05
DecimalFormat: 262144.06
Big Decimal: 262144.06
I have the problem that when converting the values with the "DecimalFormat" as well as with the "BigDecimal" -approach, i get sometimes different values (or at least ones i would not excpect)
Why is 262144.05 (Double) converting to 262144.06 (Float) and not to 262144.05 (Float)?