'c#: how to force trailing zero in numeric format string?
I need to display float as
1.00
1.50
1.55
1.60
The following is what I see using f2 format.
1.
1.5
1.55
1.6
Is there a way to force the trailing 0 to appear?
(I'm using a DevExpress SpinEdit control and trying to set the display and edit format.)
Solution 1:[1]
yourNumber.ToString("N2");
Solution 2:[2]
You can use syntax like this:
String.Format("{0:0.00}", n)
Solution 3:[3]
On those rare occasions I need to formatting, I go here:
http://blog.stevex.net/index.php/string-formatting-in-csharp/
Solution 4:[4]
For future reference,
Solution 5:[5]
spinEdit.Properties.DisplayFormat.FormatType = FormatType.Numeric;
spinEdit.Properties.DisplayFormat.FormatString = "C2";
In the future, though, I would recommended searching Dev Express' knowledge base or emailing support ([email protected]). They'll be able to answer your question in about a day.
Solution 6:[6]
You can also do this with string interpolation (note that this is C# 6 and above):
double num = 98765.4;
Console.WriteLine($"{num:0.00}"); //Replace "0.00" with "N2" if you want thousands separators
Solution 7:[7]
Let's say you had a variable called "myNumber" of type double:
double myNumber = 1520;
Instead of:
myNumber.ToString("N2"); // returns "1,520.00"
I would opt for:
myNumber.ToString("0.00"); // returns "1520.00"
since N2 will add "," thousands separators, which can often cause problems downstream.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | LukeH |
| Solution 2 | Vadim |
| Solution 3 | cookre |
| Solution 4 | z3r0 c001 |
| Solution 5 | Josh Kodroff |
| Solution 6 | derekantrican |
| Solution 7 | Michael Royer |
