2

"How to convert a float to a string with exactly one decimal"

This question has been asked many times, and the usual answer is MyFloat.ToString("0.0") or something similar. However, the problem I am facing with this is that

float f = 1;
string s = f.ToString("0.0");
MessageBox.Show(s);

outputs 1,0 but what I need is 1.0. I could of course manually replace the comma with a dot afterwards, but I'm pretty sure that that wouldn't be the proper way to do it. I wasn't able to find a solution on the internet because everywhere it says that this already outputs 1.0 How come?

LastExceed
  • 103
  • 2
  • 7
  • and [this](http://stackoverflow.com/questions/9160059/set-up-dot-instead-of-comma-in-numeric-values), and [this](http://stackoverflow.com/questions/3870154/c-sharp-decimal-separator) ... – Pikoh Apr 12 '17 at 15:52

3 Answers3

5

You can use InvariantCulture with ToString:

string s = f.ToString("0.0", CultureInfo.InvariantCulture);

Decimal separator depends on the culture but InvariantCulture uses . which is what you want.

Selman Genç
  • 97,365
  • 13
  • 115
  • 182
1

Use for example InvariantCulture

string s = f.ToString("0.0", CultureInfo.InvariantCulture);
Flat Eric
  • 7,827
  • 9
  • 34
  • 44
0

Generic solution is: to change NumberDecimalSeparator in current culture:

System.Globalization.CultureInfo customCulture = (System.Globalization.CultureInfo)System.Threading.Thread.CurrentThread.CurrentCulture.Clone();
customCulture.NumberFormat.NumberDecimalSeparator = ".";
System.Threading.Thread.CurrentThread.CurrentCulture = customCulture;
float value1 = 3.55f;
String message = String.Format("Value is {0}", value1); 
Console.Write(message); //--> "Value is 3.55"
P.K.
  • 1,745
  • 5
  • 23
  • 59