How to Nicely Format Floating Numbers to String Without Unnecessary Decimal 0'S

How to nicely format floating numbers to string without unnecessary decimal 0's

If the idea is to print integers stored as doubles as if they are integers, and otherwise print the doubles with the minimum necessary precision:

public static String fmt(double d)
{
if(d == (long) d)
return String.format("%d",(long)d);
else
return String.format("%s",d);
}

Produces:

232
0.18
1237875192
4.58
0
1.2345

And does not rely on string manipulation.

C# How to nicely format floating numbers to String without unnecessary decimal 0?

You can use the 0.############ format. Add as many # as decimal places you think you may have (decimals will be rounded off to those many places):

string output = number.ToString("0.############");  

Sample fiddle: https://dotnetfiddle.net/jR2KtK

Or you can just use the default ToString(), which for the given numbers in en-US culture, should do exactly what you want:

string output = number.ToString();  

Java String format float with and without 0

You can use DecimalFormat with # symbol:

DecimalFormat df = new DecimalFormat("#.#");
System.out.println(df.format(2.1f)); // 2.1
System.out.println(df.format(2.0f)); // 2

Formatting floats without trailing zeros

Me, I'd do ('%f' % x).rstrip('0').rstrip('.') -- guarantees fixed-point formatting rather than scientific notation, etc etc. Yeah, not as slick and elegant as %g, but, it works (and I don't know how to force %g to never use scientific notation;-).

How to format floating numbers to string without unnecessary decimal 0?

Use parseFloat - it will take care of any floating 0

alert(parseFloat("12.00")); //12

Format a double to omit unnecessary .0 and never round off

I use the following

double d =
String s = (long) d == d ? "" + (long) d : "" + d;

if you need Double instead for double. (Personally I would avoid using the wrapper if you can)

Double d =
String s = d.longValue() == d ? "" + d.longValue() : "" + d;

Format float to show decimal places if is not zero java

To display decimals the way you desire, use the following snippet:

// This is to show symbol . instead of ,
DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(Locale.US);
// Define the maximum number of decimals (number of symbols #)
DecimalFormat df = new DecimalFormat("#.##########", otherSymbols);

// type: double
System.out.println(df.format(5.0)); // writes 5
System.out.println(df.format(7.3)); // writes 7.3
System.out.println(df.format(9.000003)); // writes 9.000003

// type: float
System.out.println(df.format(9.000003f)); // writes 9.000002861


Related Topics



Leave a reply



Submit