Reputation: 5851
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
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
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
Reputation: 159854
You can use DecimalFormat
:
System.out.println(new DecimalFormat("0.#").format(12.0));
Upvotes: 7