I need to store a float with n decimals in a variable but it seems too complicated.
If I run this code:
float testFloat = -18.479999542236328f;
System.out.println(getFloatAsStringIWithNDecimals(testFloat, 9));
System.out.println(testFloat + "");
System.out.println(getFloatAsStringIWithNDecimals(testFloat, 3));
System.out.println(getFloatWithNDecimals(testFloat, 3));
System.out.println(Float.parseFloat(getFloatAsStringIWithNDecimals(testFloat, 3)));
System.out.println(getFloatAsStringIWithNDecimals(Float.parseFloat(getFloatAsStringIWithNDecimals(testFloat, 3)), 9));
System.out.println(getFloatWithNDecimals(Float.parseFloat(getFloatAsStringIWithNDecimals(testFloat, 3)), 3));
System.out.println(getFloatAsStringIWithNDecimals(getFloatWithNDecimals(Float.parseFloat(getFloatAsStringIWithNDecimals(testFloat, 3)), 2), 9));
public static String getFloatAsStringIWithNDecimals(float f, int nDecimals) {
return String.format(Locale.US, "%.0"+nDecimals+"f", f);
}
public static float getFloatWithNDecimals(float f, int nDecimals) {
int multiplier = 1;
for(int i = 1; i <= nDecimals; i++) {
multiplier *= 10;
}
return ( (int)(f * multiplier) ) *1f / multiplier;
}
public static float getFloatWithNDecimals(float f) {
return getFloatWithNDecimals(f, 2);
}
this is the output:
-18.479999542
-18.48
-18.480
-18.48
-18.48
-18.479999542
-18.48
-18.479999542
Why do these output, even if I truncate the decimals, cast them to int and then divide them by 100 and even if I truncate them by converting the float to String using String.format
?
Thanks