C# 字符串型转数字型

// 当需要将字符串格式的数字转为数字时候,我们会用到的函数为Convert.ToDouble(),
// 然而当你的字符串为49,9时,由于包含了逗号,函数会将逗号忽略,直接转为499,
// 所以我们需要使用provider,
// provider是一个获取NumberFormatInfo对象IFormatProvider实例
// 所述的NumberFormatInfo对象提供有关的格式的区域性特定信息


using
System; using System.Globalization; class Example { static void Main() { // Create a NumberFormatInfo object and set some of its properties. NumberFormatInfo provider = new NumberFormatInfo(); provider.NumberDecimalSeparator = ","; provider.NumberGroupSeparator = "."; provider.NumberGroupSizes = new int[] { 3 }; // Define an array of numeric strings to convert. String[] values = { "123456789", "12345.6789", "12345,6789", "123,456.789", "123.456,789", "123,456,789.0123", "123.456.789,0123" }; Console.WriteLine("Default Culture: {0} ", CultureInfo.CurrentCulture.Name); Console.WriteLine("{0,-22} {1,-20} {2,-20} ", "String to Convert", "Default/Exception", "Provider/Exception"); // Convert each string to a Double with and without the provider. foreach (var value in values) { Console.Write("{0,-22} ", value); try { Console.Write("{0,-20} ", Convert.ToDouble(value)); } catch (FormatException e) { Console.Write("{0,-20} ", e.GetType().Name); } try { Console.WriteLine("{0,-20} ", Convert.ToDouble(value, provider)); } catch (FormatException e) { Console.WriteLine("{0,-20} ", e.GetType().Name); } } } } // The example displays the following output: // Default Culture: en-US // // String to Convert Default/Exception Provider/Exception // // 123456789 123456789 123456789 // 12345.6789 12345.6789 123456789 // 12345,6789 123456789 12345.6789 // 123,456.789 123456.789 FormatException // 123.456,789 FormatException 123456.789 // 123,456,789.0123 123456789.0123 FormatException // 123.456.789,0123 FormatException 123456789.0123

 Convert.ToDouble() 官网参考链接:

https://msdn.microsoft.com/en-us/library/9s9ak971(v=vs.110).aspx

原文地址:https://www.cnblogs.com/ryanzheng/p/8777240.html