I want to round float to a given precision. For example:
0,6667 to 0,67
0,004 to 0,00
0,328 to 0,33
I know I can round a float to integer, for example:
0,06 to 0
Is there any way to achieve this?
I want to round float to a given precision. For example:
0,6667 to 0,67
0,004 to 0,00
0,328 to 0,33
I know I can round a float to integer, for example:
0,06 to 0
Is there any way to achieve this?
Format a floating point number to a string with a specified number of decimal places using String.format(...)
.
Example:
String.format("%.2f", myFloatingPointValue);
Do you need the rounding for display or for calculations?
If it's for display you can use this:
DecimalFormat df = new DecimalFormat("##.00");
float f = (float) 4.234432;
System.out.println(df.format(f));
For calculations, you could do it like this:
float f = (float) 4.234432;
BigDecimal bd = new BigDecimal(f);
bd = bd.setScale(2, RoundingMode.HALF_UP);
f = bd.floatValue();