float.Parse fails on decimals and commas

前端 未结 2 1821
轻奢々
轻奢々 2020-12-31 11:26

When I try this line:

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


        
相关标签:
2条回答
  • 2020-12-31 11:57

    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);
    
    0 讨论(0)
  • 2020-12-31 12:14
    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");
                    }
                });
    
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题