本文介绍了C#转换对象为十进制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图将对象转换为值 0.39999999999999997
来小数变量不失precision。
I'm trying to convert an object with the value 0.39999999999999997
to a decimal variable without losing the precision.
object d = 0.39999999999999997;
我尝试下面的方法。
I've tried the following methods.
decimal val1 = Convert.ToDecimal(d); // val1 = 0.4
object val2 = Convert.ChangeType(d, Type.GetType("System.Decimal")); // val2 = 0.4
decimal val3 = decimal.Parse(d.ToString()); // val3 = 0.4
decimal val4 = (Decimal) d; // val4 = 0.4
我知道这是不是与十进制数据类型不能够如下所示存储该值的问题。
I know the this is not a problem with the decimal data type not being able to store this value as illustrated below.
decimal val5 = 0.39999999999999997m; // val5 = 0.39999999999999997;
我如何将此对象转换为十进制不失precision?
How do I convert this object to decimal without losing the precision?
我使用的.NET Framework 3.5,如果该事项。
I'm using .NET Framework 3.5 if that matters.
推荐答案
我觉得这是code您寻找:
I think this is the code you looking for:
object d = 0.39999999999999997;
//Unbox value
double doubleVal = (double)d;
//Convert to string. R format specifier gives a string that can round-trip to an identical number.
//Without R ToString() result would be doubleAsString = "0.4"
string doubleAsString = doubleVal.ToString("R");
//Now that you have doubleAsString = "0.39999999999999997" parse it!
decimal decimalVal = decimal.Parse(doubleAsString);
这篇关于C#转换对象为十进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!