Srujan Kumar Gulla
Srujan Kumar Gulla

Reputation: 5851

Number Format in java

Is there a way to do a format on double to String in java where i would want the output as:

Intended output:

if n=12.4 => 12.4
if n=12.0 -> 12

I was using String.valueof(n) with returns Current output:
if n=12.4 => 12.4
if n=12.0 => 12.0

Any help will be appreciated.

Upvotes: 1

Views: 139

Answers (3)

Puppet Master 3010
Puppet Master 3010

Reputation: 261

to format double to string with two decimal places use code like this

String.format("%1$,.2f", doubleValue)

for int use this

String.format("%d", intValue );

Upvotes: 0

Kyle
Kyle

Reputation: 893

A while ago I wrote this, and it worked well

    public static String formattedDouble(double d)
    {
        Long l = (d == Math.floor(d)) ? (long)d : null;
        String str = "";
        if (l == null)
            str += d;
        else
            str += l;
        return str;
    }

Upvotes: 0

Reimeus
Reimeus

Reputation: 159854

You can use DecimalFormat:

System.out.println(new DecimalFormat("0.#").format(12.0));

Upvotes: 7

Related Questions