Special decimal formatting
Is there a string format that can be used in decimal to get the following results?
123 => "123" 123.4 => "123.40" 123.45 => "123.45" 123.456 => "123.46" In English, the number should always be displayed with exactly two decimal places, unless it contains an integer value, when it does not have to be decimal places (therefore, the display "123.00" is not allowed).
I do not know this format, I'm afraid. You may need to use:
string text = (d == (int) d) ? ((int) d).ToString() : d.ToString("N2"); EDIT: The above code will only work when d is in the range between int.MinValue and int.MaxValue . Obviously, you can do better than using long , but if you want to cover the entire decimal range, you will need something more powerful.
Perhaps this is not ideal, but the starting point. Just format up to two decimal places and replace any .00 with an empty string.
decimal a = 123; decimal b = 123.4M; decimal c = 123.456M; Debug.Assert(a.ToString("0.00").Replace(".00", "") == "123"); Debug.Assert(b.ToString("0.00").Replace(".00", "") == "123.40"); Debug.Assert(c.ToString("0.00").Replace(".00", "") == "123.46"); You must first use the Math.Round method, and then use the toString () transform
//123.456 => "123.46" myDecimal = Math.Round(myDecimal, 2); The second parameter is the number of decimal places to round to and then do the following:
myDecimal.ToString(); There is no real need for N2 in fact, so you show the numbers "as is" after rounding, i.e. 124 if there are no decimal places after the point, or 123.46 after rounding 123.456