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?
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);
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");
}
});
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With