0

I tested a very basic program with a few lines in main.

 float x = 1;
 x =  float.Parse("4.5");
 Console.WriteLine(x);

The output is 45

It leaves out the decimal point for some reason. I must use float for my program, how can I solve this?

Thomas Weller
  • 55,411
  • 20
  • 125
  • 222

1 Answers1

3

The way the parsing works depends on the culture the system the program is running on. It is likely that the language have set as display language doesn't use decimal point as the fraction separator.

If you want to use a specific culture (for example US), which uses decimal point, you must specify it in the second parameter of the Parse method.

For example to force use "en-US" culture :

CultureInfo culture = new CultureInfo("en-US");
double number = Double.Parse("4.5", culture);

You can also use invariant culture, you can use CultureInfo.InvariantCulture instead. It is loosely based on US culture, but it is not exactly that (for example currency is different). See documentation for more info.

Martin Zikmund
  • 38,440
  • 7
  • 70
  • 91