Displaying trailing zeros except when a whole number
Is there a way (in .NET) of removing trailing zeros from a number when using 开发者_开发问答.ToString("...")
, but to display to 2 decimal places if the number is not a whole number:
- (12345.00).ToString(...) should display as 12345
- (12345.10).ToString(...) should display as 12345.10
- (12345.12).ToString(...) should display as 12345.12
Is there 1 number format string that will work in all these scenarios?
.ToString("#.##")
nearly works but doesn't show the trailing 0 for scenario 2...
Also, other cultures aren't an issue, i just want a decimal point (not a comma etc.)
Something along these lines?
if (number % 1 == 0)
Console.WriteLine(string.Format("{0:0}", number));
else
Console.WriteLine(string.Format("{0:0.00}", number));
EDIT
There is a little bug in this code though:) 1.001 will be printed as "1.00"... this may not be what you want, if you need to print 1.001 as "1" you'll need to change the if(...) test to check for a finite tolerance. As this question is more about the formatting I will leave the answer unchanged but in production code you might want to consider this kind of issue.
Dirty way:
string.Format("{0:0.00}", number).Replace(".00","")
Not in one format but it fits in one line:
double a = 1.0;
string format = string.Format((a == (int)a) ? "{0:0}" : "{0:0.00}", a);
I can't say I've come across a single mask that will do that. I would use
string output = (value % 1 > 0) ? String.Format("{0:0.00}", value) : String.Format("{0:0.##}", value);
You could write an extension method like this to do the formatting for you:
public static string FormatNumberString(this double input)
{
int temp;
string inputString = input.ToString();
return Int32.TryParse(inputString, out temp) ? inputString : input.ToString("0.00");
}
If you were looking to do this in ASP MVC Razor then you could try this
@string.Format(item.DecimalNumber % 1 == 0 ? "{0:0}" : "{0:0.00}", item.DecimalNumber)
This will behave like so:
Value: 2.5 --> Display: 2.50
Value: 5 --> Display: 5
Value: 2.45 --> Display: 2.45
I guess you could do your very own method to produce that display, since it's conditional to whether or not it is an integer.
public static class Extensions
{
public static string ToCustomString(this decimal d)
{
int i = (int)d;
if (i == d)
return i.ToString();
return d.ToString("#.00");
}
}
If you want to use it to display currency, you can use following
float fVal = 1234.20f;
String strVal = fVal.Tostring("c");
精彩评论