0

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?

Oleksandr Firsov
  • 1,340
  • 1
  • 17
  • 45
  • Try using the solution found here http://stackoverflow.com/questions/153724/how-to-round-a-number-to-n-decimal-places-in-java?rq=1 – Dan Harms Apr 12 '14 at 15:17

2 Answers2

1

Format a floating point number to a string with a specified number of decimal places using String.format(...).

Example:

String.format("%.2f", myFloatingPointValue);
Hidde
  • 9,683
  • 7
  • 38
  • 64
0

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();
wvdz
  • 15,266
  • 3
  • 43
  • 82