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.

4

4 回答 4

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.

于 2013-05-06T22:23:57.183 回答
0

You can use DecimalFormat

System.out.println(new DecimalFormat("0.00").format(xFunction(94)));
于 2013-05-06T22:24:09.617 回答
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 );

于 2013-05-06T22:26:57.273 回答
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.

于 2013-05-06T22:31:33.537 回答