3

I have used the following function

float val=0.0;
DecimalFormat toTheFormat = new DecimalFormat("#.##");
float value=Float.valueOf(toTheFormat.format(val));

But its not suitable for all conditions like "0.0" still "0.0". Its not scale up to "0.00".

Anto Robinson
  • 463
  • 5
  • 12

4 Answers4

13

Use

DecimalFormat toTheFormat = new DecimalFormat("0.00");

to round to 2 significant digits

Reimeus
  • 158,255
  • 15
  • 216
  • 276
4

try

DecimalFormat toTheFormat = new DecimalFormat("#.00");
sunysen
  • 2,265
  • 1
  • 12
  • 13
1

Your approach is mistaken. Rounding is a numeric operation that takes a number x and returns another number y which approximates x and has the property that the decimal expansion has only so many digits. Example:

0.123 --> 0.12

But 0.0 and 0.00 are the exact same numbers, there is no point in rounding. What you (maybe) want is to format a number in a certain way on output. For this, see the other answers.

Ingo
  • 36,037
  • 5
  • 53
  • 100
1

If I use DecimalFormat toTheFormat = new DecimalFormat("#.00");

am getting output as .00 not 0.00

so this would be the correct code

DecimalFormat toTheFormat = new DecimalFormat("#0.00");

Anto Robinson
  • 463
  • 5
  • 12