Zygmuntix
Zygmuntix

Reputation: 359

How to format double in C# to such format?

I have problem with formatting double in C#. I want to achieve format like this: 2.0, but I get an exception.

string result = string.Format("{0.0}",  2.0d);

I get Format Exception, Input string was not in a correct format. When I change code to:

string result = string.Format("{0:0.0}",  2.0d);

I get comma, not drop as separator. Is there some way to get 2.0 from string.format without any other functions?

Upvotes: 1

Views: 901

Answers (4)

Juan
Juan

Reputation: 588

Try this, putting the culture that u prefer:

string result = string.Format(new System.Globalization.CultureInfo("en-GB"),"{0:0.0}", 2.0d);

Upvotes: 1

Henk Holterman
Henk Holterman

Reputation: 273244

  string.Format(CultureInfo.InvariantCulture, "{0:0.0}",  2.0d);

Upvotes: 1

Saeb Amini
Saeb Amini

Reputation: 24400

You are getting a comma because of your system's locale. If you'd like to always get a ., specify culture invariance:

string result = string.Format(CultureInfo.InvariantCulture, "{0:N1}", 2.0d);

Have a look at Standard Numeric Format Strings.

Upvotes: 2

toadflakz
toadflakz

Reputation: 7944

Try this instead of using String.Format():

var param = 2.0d
string result = param.ToString("N1");

Upvotes: 1

Related Questions