Decimal 存储 C# 中解析字符串的精度?有什么影响?

2024-07-04

在 IRC 的一次对话中,有人指出了以下几点:

decimal.Parse("1.0000").ToString() // 1.0000
decimal.Parse("1.00").ToString() // 1.00

如何/为什么decimal类型像这样保留精度(或者更确切地说,有效数字)?我的印象是这两个值是相等的,而不是不同的。

这也引发了进一步的问题:

  • 数学运算时有效数字的位数是如何确定的?
  • 序列化期间是否保留有效数字的数量?
  • 当前的文化是否会影响处理此问题的方式?

数学运算时有效数字的位数是如何确定的?

这是在ECMA-334 http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-334.pdfC# 4 规范 11.1.7 第 112 页

小数表示为按十的幂缩放的整数。为了 绝对值小于1.0m的小数,该值精确到 至少小数点后第 28 位。对于有绝对值的小数 大于或等于1.0m,该值至少精确到28 数字。

序列化期间是否保留有效数字的数量?

是的,序列化后,值及其精度不会改变

[Serializable]
public class Foo
{
    public decimal Value;
}

class Program
{
    static void Main(string[] args)
    {
        decimal d1 = decimal.Parse("1.0000");
        decimal d2 = decimal.Parse("1.00");

        Debug.Assert(d1 ==d2);

        var foo1 = new Foo() {Value = d1};
        var foo2 = new Foo() {Value = d2};

        IFormatter formatter = new BinaryFormatter();
        Stream stream = new FileStream("data.bin", FileMode.Create, FileAccess.Write, FileShare.None);
        formatter.Serialize(stream, d1);
        stream.Close();

        formatter = new BinaryFormatter();
        stream = new FileStream("data.bin", FileMode.Open, FileAccess.Read, FileShare.Read);
        decimal deserializedD1 = (decimal)formatter.Deserialize(stream);
        stream.Close();

        Debug.Assert(d1 == deserializedD1);

        Console.WriteLine(d1); //1.0000
        Console.WriteLine(d2); //1.00
        Console.WriteLine(deserializedD1); //1.0000

        Console.Read();
    }
}

当前的文化是否会影响处理此问题的方式?

当前区域性仅影响如何从字符串中解析小数,例如它可以处理'.' or ','作为特定于文化的小数点符号或货币符号,您是否应该提供它,例如“123.4500 英镑”。文化不会改变对象内部存储的方式,也不会影响其精度。

在内部,小数有 http://csharpindepth.com/Articles/General/Decimal.aspx一个尾数、一个指数和一个符号,所以没有空间容纳其他任何东西。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Decimal 存储 C# 中解析字符串的精度?有什么影响? 的相关文章

随机推荐