1

How to get double value printed in formatted string with minimal precision? Example:

double v = 2.02;
String.format("%f", v);

Default %f format always prints 6 digits after point => "2.020000". What I need is

42.0  => "42"
2.02  => "2.02"
0.3333333333333333 => "0.3333333333333333"

The best I can get so far is String.valueOf(v)

String.format("%s", String.valueOf(v));

That pass all tests except "42". Any ideas on easy way to do all three tests?

smile-on
  • 2,073
  • 1
  • 20
  • 20

1 Answers1

0

As pointed by Yassin, there is a ggod way by custom formatted:

public static String fmt(double d)
{
    if(d == (long) d)
        return String.format("%d",(long)d);
    else
        return String.format("%s",d);
}
smile-on
  • 2,073
  • 1
  • 20
  • 20
  • `String.format("%s",d)`??? Talk about unnecessary overhead. Use `Double.toString(d)`. Same for the other: `Long.toString((long)d)`. – Andreas Oct 14 '15 at 22:57