Home > Mobile >  How to convert string with comma to float in .net?
How to convert string with comma to float in .net?

Time:05-11

var withComma = Convert.ToSingle("3,2");
Console.WriteLine($"Converted float from string with comma (3,2): {withComma}");

It returns to the console:

Converted float from string with comma (3,2): 32

But should return:

Converted float from string with comma (3,2): 3.2

How can I convert it to float and make the result to be 3.2?

CodePudding user response:

https://dotnetfiddle.net/TnQyL9

Console.WriteLine(float.Parse("3,2", System.Globalization.CultureInfo.GetCultureInfo("es-ES")));

prints: 3.2

There is a lot of cultures which have this format. Just pick one you are fine with.

CodePudding user response:

Finally I'm using this approach

private void convertToFloat(string str) 
{
    float result = float.Parse(str.Replace(',', '.'));
    Console.WriteLine(result);
}
  • Related