1

I have the following and the question is, for example if zzi = 95 then myNum will be correctly displayed as 32.33, exactly as I want it too with two decimal places.

However if zzi = 94, myNum will be displayed as 32.0 instead of 32.00

How to display it as 32.00?

float xFunction(int zzi) {

    float myNum = (zzi + 2);
    myNum = myNum / 3;
    int precision = 100; // keep 4 digits
    myNum = (float) (Math.floor(myNum * precision + .5) / precision);
    return myNum;
}

Thanks before.

Hovercraft Full Of Eels
  • 276,051
  • 23
  • 238
  • 346
MelvinTerence
  • 13
  • 1
  • 3

4 Answers4

3

Your question is not so much about rounding a number as it is about rounding a display or String representation of a number. The solution:

  • Use new DecimalFormat("0.00");
  • Or String.format("%.2f", myNumber);
  • Or new java.util.Formatter("%.2f", myNumber);
  • Or System.out.printf("%.2f", myNumber);

Note: avoid use of float whenever possible, and instead prefer use of double which greatly improves numeric precision at little cost. For financial calculations use neither but instead opt for integer calculations or use BigDecimal.

Hovercraft Full Of Eels
  • 276,051
  • 23
  • 238
  • 346
0

You can use DecimalFormat

System.out.println(new DecimalFormat("0.00").format(xFunction(94)));
Reimeus
  • 152,723
  • 12
  • 195
  • 261
0

Remember:

1) printing the number displaying two decimal places is very different from rounding the actual value. In other words "representation" != actual value.

2) floating point values are always imprecise. Even with rounding, you may or may not get an "exact value".

Having said that, the simplest approach is:

float myNum = ((123.456 * 100.0) + .5) / 100.0;

new DecimalFormat("#.##").format(myNum );

paulsm4
  • 99,714
  • 15
  • 125
  • 160
0

You should work on the printing function. I assume you are using a System.out.println: replace it with

System.out.format("%.2f", numberToPrint);

Read the docs for that function to discover more about format strings.

Stefano Sanfilippo
  • 29,175
  • 7
  • 71
  • 78