Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

float.Parse fails on decimals and commas

Tags:

c#

parsing

When I try this line:

float f = float.Parse(val, System.Globalization.NumberStyles.AllowDecimalPoint | System.Globalization.NumberStyles.AllowThousands);

where val is a string set to "5.267" without the quotes, I get this error:

FormatException: Unknown char: . System.Double.Parse (System.String s, NumberStyles style, IFormatProvider provider) System.Single.Parse (System.String s, NumberStyles style)

So I tried changing the decimal point to a comma, like: 5,267 and got this error:

FormatException: Unknown char: , System.Double.Parse (System.String s, NumberStyles style, IFormatProvider provider) System.Single.Parse (System.String s, NumberStyles style)

I....don't....understand. As far as I can tell I'm doing this right. It's a simple thing, so why is it giving me such grief?

like image 248
damocles Avatar asked Oct 17 '12 19:10

damocles


2 Answers

Parse is culture aware. If your local culture has different requirements, then you may want to pass a culture or other format provider in. Try using CultureInfo.InvariantCulture. You won't need the decimal option if you do.

float f = float.Parse(val,
                      System.Globalization.NumberStyles.AllowThousands,
                      CultureInfo.InvariantCulture);
like image 78
Matt Johnson-Pint Avatar answered Oct 25 '22 19:10

Matt Johnson-Pint


using System;
using System.Collections.Generic;
using System.Globalization;

namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {

            var numList = new List<string>(){"0", "-6e-5", "78.56238", "05.56", "0.5E9", "-45,000.56", "", ".56", "10.4852,64"};
            numList.ForEach(num =>
            {
                // If we use NumberStyles.Float => -45,000.56 is invalid
                if (decimal.TryParse(num, NumberStyles.Any, CultureInfo.InvariantCulture, out decimal result))
                {
                    Console.WriteLine(result);
                }
                else
                {
                    Console.WriteLine(num + " is not a valid number");
                }
            });

        }
    }
}
like image 35
J-K dad Avatar answered Oct 25 '22 21:10

J-K dad