Display trailing zeros except integer

Is there a way (in .NET) to remove trailing zeros from a number when using .ToString("...") , but to display up to two decimal places if the number is not an integer:

  • (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 one line of format format that will work in all of these scenarios?

.ToString("#.##") almost works, but does not show a terminating 0 for scenario 2 ...

Also, other cultures are not a problem, I just want a decimal point (not a comma, etc.)

+7
c #
source share
8 answers

Something like that?

  if (number % 1 == 0) Console.WriteLine(string.Format("{0:0}", number)); else Console.WriteLine(string.Format("{0:0.00}", number)); 

EDIT

There is a small error in this code: :) ​​1.001 will be printed as "1.00" ... it may not be what you want, if you need to print 1.001 as "1", you will need to change if (...) the test to check the final tolerance. Since this question is more about formatting, I will leave the answer unchanged, but in production code you can consider this kind of problem.

+7
source share

Dirty way:

 string.Format("{0:0.00}", number).Replace(".00","") 
+2
source share

Not in one format, but it fits on one line:

 double a = 1.0; string format = string.Format((a == (int)a) ? "{0:0}" : "{0:0.00}", a); 
+1
source share

I can’t say that I came across one mask that will do this. I would use

 string output = (value % 1 > 0) ? String.Format("{0:0.00}", value) : String.Format("{0:0.##}", value); 
0
source share

I suggest that you can make your own method to create this mapping, since it depends on whether 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"); } } 
0
source share

If you want to use it to display currency, you can use the following

 float fVal = 1234.20f; String strVal = fVal.Tostring("c"); 
0
source share

You can write an extension method like this for formatting:

 public static string FormatNumberString(this double input) { int temp; string inputString = input.ToString(); return Int32.TryParse(inputString, out temp) ? inputString : input.ToString("0.00"); } 
0
source share

If you want to do this in ASP MVC Razor, you can try this

 @string.Format(item.DecimalNumber % 1 == 0 ? "{0:0}" : "{0:0.00}", item.DecimalNumber) 

It will look like this:

Value: 2.5 β†’ Display: 2.50

Value: 5 β†’ Display: 5

Value: 2.45 β†’ Display: 2.45

0
source share

All Articles