1

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?

Selman Genç
  • 100,147
  • 13
  • 119
  • 184
Zygmuntix
  • 339
  • 3
  • 13

4 Answers4

2

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.

Saeb Amini
  • 23,054
  • 9
  • 78
  • 76
1

Try this instead of using String.Format():

var param = 2.0d
string result = param.ToString("N1");
toadflakz
  • 7,764
  • 1
  • 27
  • 40
1
  string.Format(CultureInfo.InvariantCulture, "{0:0.0}",  2.0d);
H H
  • 263,252
  • 30
  • 330
  • 514
1

Try this, putting the culture that u prefer:

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