Reputation: 5832
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:
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.)
Upvotes: 10
Views: 5545
Reputation: 3848
Dirty way:
string.Format("{0:0.00}", number).Replace(".00","")
Upvotes: 3
Reputation: 527
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
Upvotes: 1
Reputation: 8511
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.
Upvotes: 6
Reputation: 4485
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");
}
Upvotes: 1
Reputation: 3219
If you want to use it to display currency, you can use following
float fVal = 1234.20f;
String strVal = fVal.Tostring("c");
Upvotes: 0
Reputation: 5036
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");
}
}
Upvotes: 0
Reputation: 17964
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);
Upvotes: 2
Reputation: 2522
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);
Upvotes: 1