c# - 小数存储 C# 中已解析字符串的精度?有什么影响?

标签 c# string decimal string-formatting

在 IRC 上的一次对话中,有人指出了以下内容:

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

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

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

  • 在数学运算中如何确定有效数字的个数?
  • 在序列化过程中是否保留了有效数字的数量?
  • 当前的文化是否会影响处理方式?

最佳答案

在数学运算中如何确定有效数字的个数?

这在 ECMA-334 中指定C# 4 规范 11.1.7 p.112

A decimal is represented as an integer scaled by a power of ten. For decimals with an absolute value less than 1.0m, the value is exact to at least the 28th decimal place. For decimals with an absolute value greater than or equal to 1.0m, the value is exact to at least 28 digits.

序列化过程中是否保留有效数字?

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

[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();
    }
}

当前的文化会影响处理方式吗?

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

在内部,decimal has一个尾数、一个指数和一个符号,所以没有其他空间了。

关于c# - 小数存储 C# 中已解析字符串的精度?有什么影响?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8705861/

相关文章:

c# - 生成数字并在内存中选择

c# - WCF 服务可以替代 TCPListener 的功能吗?

java - 如何测试一个字符是否不在字符串中? (java, junit)

vb.net - 如何通过 "String Name"获取控制属性?

java - 如何在 Java 中将数字四舍五入到 n 位小数

C# 在泛型类中调用方法

c# - 使用OutputFormatterWriteContext.WriterFactory输出带有BOM的UTF-8

c# - 为什么这会出现在我的 C# 字符串 : £ 中

JavaScript 接收伪整数(即 0100 或 03)并输出正确整数的函数

mysql - PHP : MySql Data Type for monetary values