0

How to round off a float value if the value is like:

eg:

  • 1.0 ==> then it should return 1
  • 2.0 ==> then it should return 2

but if the value is like:

  • 1.2 ==> then it should return 1.2

  • 1.90 ==>then it should return 1.9

I have tried to round off it and also tries different solutions but that doesn't worked for me.

Pravesh
  • 822
  • 1
  • 8
  • 20
  • 2
    What Every Computer Scientist Should Know About Floating-Point Arithmetic http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html – Klas Lindbäck May 22 '15 at 12:30
  • The trailing zero is just part of the output when you print it. How did you print it? – aioobe May 22 '15 at 12:31
  • 1
    What you want is impossible, given how IEEE floating point works. You must use some explicit code to format the number the way you want it. – Hot Licks May 22 '15 at 12:34
  • If you meant formatting without trailing zeros, that's what `#` does ([demo](http://ideone.com/f7BWOo)). – Sergey Kalinichenko May 22 '15 at 12:39
  • @pks `Math.round(1.1555)` does not work, but `round(1.1555, 2)` from [here](http://stackoverflow.com/q/2808535/335858) does ([demo](http://ideone.com/dC5g4V)). – Sergey Kalinichenko May 22 '15 at 13:22

2 Answers2

2

You can create a helper function like this

 static public void Normalize(String pattern, double value ) {
    DecimalFormat formatter = new DecimalFormat(pattern);
    String normalizedValue = formatter.format(value);
    System.out.println(normalizedValue);
    }

Normalize("0.#####",2.40); // 2.4
Normalize("0.#####",2.0); // 2

This worked for me.

Rockstar
  • 2,228
  • 3
  • 20
  • 39
0

What you're talking about here is a display issue. The "0" in the 1.0 shows how accurate the number is, if you are only displaying 1 then the person reading does not know how accurate that value is (compared with 1.1, 1.9 or even 1.0003).

My suggestion would be to convert your answer to a string and check if the last value is "0", and if so remove it for display purposes (or some other formatting solution).

Note: I wouldn't recommend doing this because it changes the meaning of the value.

KerSplosh
  • 466
  • 8
  • 26
  • What you're saying is true in the scientific sense, but you miss the point, since floating point number implementations aren't accurate representations, so eg. 1+1 could equal 2.00000000000001 or 1.9999999999 (thought examples) – Anders R. Bystrup May 22 '15 at 12:51
  • @Anders The above is just an answer to the OPs question. I understand the reasons for wanting to display things differently, but I wrote how I would do it and why I would not recommend that approach (based on the example). – KerSplosh May 22 '15 at 12:57
  • Fair enough, but java will output 2.0 no matter if you do `System.out.println( 2.0 )` or `System.out.println( 2.000000 )`.... – Anders R. Bystrup May 22 '15 at 13:12