这个简单的程序
using System.IO;
using System;
using System.ComponentModel;
class Program
{
static void Main()
{
var smallDouble = double.MinValue;
Console.WriteLine(smallDouble);
var converter = TypeDescriptor.GetConverter(typeof(double));
var convertedValue = converter.ConvertFrom(smallDouble.ToString());
Console.WriteLine(convertedValue);
}
}
给出以下错误
sh-4.3# mono main.exe
-1.79769313486232E+308
Unhandled Exception:
System.Exception: -1.79769313486232E+308 is not a valid value for Double. ---> System.OverflowException: Number overflow.
at System.Double.Parse (System.String s, NumberStyles style, IFormatProvider provider) [0x00000] in <filename unknown>:0
at System.ComponentModel.DoubleConverter.ConvertFromString (System.String value, System.Globalization.NumberFormatInfo format) [0x00000] in <filename unknown>:0
at System.ComponentModel.BaseNumberConverter.ConvertFrom (ITypeDescriptorContext context, System.Globalization.CultureInfo culture, System.Object value) [0x00000] in <filename unknown>:0
--- End of inner exception stack trace ---
at System.ComponentModel.BaseNumberConverter.ConvertFrom (ITypeDescriptorContext context, System.Globalization.CultureInfo culture, System.Object value) [0x00000] in <filename unknown>:0
at System.ComponentModel.TypeConverter.ConvertFrom (System.Object o) [0x00000] in <filename unknown>:0
at Program.Main () [0x00000] in <filename unknown>:0
[ERROR] FATAL UNHANDLED EXCEPTION: System.Exception: -1.79769313486232E+308 is not a valid value for Double. ---> System.OverflowException: Number overflow.
at System.Double.Parse (System.String s, NumberStyles style, IFormatProvider provider) [0x00000] in <filename unknown>:0
at System.ComponentModel.DoubleConverter.ConvertFromString (System.String value, System.Globalization.NumberFormatInfo format) [0x00000] in <filename unknown>:0
at System.ComponentModel.BaseNumberConverter.ConvertFrom (ITypeDescriptorContext context, System.Globalization.CultureInfo culture, System.Object value) [0x00000] in <filename unknown>:0
这是一个错误还是我错过了什么?这是在序列化测试中提出的。
答案 0 :(得分:1)
您的解析失败,因为转换后的字符串值double.MinValue
并不完全是假设的。它越来越圆了。使用:
var convertedValue = converter.ConvertFrom(smallDouble.ToString("r"));
请参阅:The round-trip ("R") format specifier
往返(“R”)格式说明符用于确保数字 转换为字符串的值将被解析回相同的值 数值。此格式仅支持Single,Double, 和BigInteger类型。