TryParse double values

2019-07-12 18:04发布

问题:

I need validate double values. When I TryParse .00 or ,00 return false, but I allow this values must true.

This code not work correctly for this case

model = ,00 or .002 or ,789 or .12 ...

double number;
double.TryParse(model, NumberStyles.Any, NumberFormatInfo.InvariantInfo, out number)

回答1:

You could loop all supported cultures:

bool parsable = false;
double number = 0;
var supportedCultures = new[] { CultureInfo.InvariantCulture, CultureInfo.CreateSpecificCulture("de-DE") };
foreach(var culture in supportedCultures)
{
    parsable = double.TryParse(model, NumberStyles.Any, culture, out number);
    if (parsable)
        break;
}

or with LINQ:

CultureInfo thisCulture = supportedCultures
    .FirstOrDefault(c => double.TryParse(model, NumberStyles.Any, c, out number));
if (thisCulture != null)
{
    Console.WriteLine("Number was parsable to " + number);
}

old approach, too error-prone as asawyer has pointed out("1,000,000.00"):

You could replace commas with dots:

bool parsable = double.TryParse(model.Replace(",", "."), NumberStyles.Any, NumberFormatInfo.InvariantInfo, out number);



回答2:

When you use NumberFormatInfo.InvariantInfo you are forcing the parser to treat . as the decimal separator and , as the thousands separator. So

double.TryParse(".002", out number)

would return true, but

double.TryParse(",789", out number)

would not.

If you want to support multiple formats you'd have to call TryParse for each format. There's not a way to try and parse a number that would be valid in an format because they could return different value. "123,456" could be interpreted two different ways depending on what culture you were using.



回答3:

I don't think you can really do this safely. If you manage to get your system to handle both ways of defining "." and "," as the decimal separator and grouping separator, then you run into issues of ambiguity.

For instance, what if "1.001" is passed in? What about "1,001"? How do you know if either one really means "one-thousand-and one" or "one and one-thousandth"?



标签: c# tryparse