17

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.)

Josh Kodroff
  • 27,301
  • 27
  • 95
  • 148
P a u l
  • 7,805
  • 15
  • 59
  • 92

7 Answers7

32
yourNumber.ToString("N2");
LukeH
  • 263,068
  • 57
  • 365
  • 409
  • this one adds unnecessary commas for thousands, does not perfectly fit in cases with larger numbers – Andrew Dec 22 '22 at 07:25
16

You can use syntax like this:

String.Format("{0:0.00}", n)
Vadim
  • 21,044
  • 18
  • 65
  • 101
5

For future reference,

http://www.csharp-examples.net/string-format-double/

z3r0 c001
  • 119
  • 1
5

On those rare occasions I need to formatting, I go here:

http://blog.stevex.net/index.php/string-formatting-in-csharp/

cookre
  • 705
  • 1
  • 5
  • 7
4
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 (support@devexpress.com). They'll be able to answer your question in about a day.

Josh Kodroff
  • 27,301
  • 27
  • 95
  • 148
0

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
derekantrican
  • 1,891
  • 3
  • 27
  • 57
0

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.