Sunday, June 9, 2013

Properly format java floating points or double while displaying

The question being addressed here is how to print these doubles or floats nicely in Java?
String.format("%f", value) works in most cases, but there will be a lot of trailing zeros for small values.

Here's an example output of of %f
55.00000000
0.18000000000
1237875192.0
4.58900000000
0.00000000
1.23450000

Instead, the desired output is:
232
0.18
1237875192
4.589
0
1.2345

Here is the piece of code that can do this efficiently and correctly:

public static String fmtDouble(double inp){    if(inp == (int)inp)        return String.format("%d",(int)inp);    else        return String.format("%s",inp);}
Also this mechanism does not require any separate string manipulation. This solution is based on a code snippet I read somewhere.

0 comments:

Post a Comment