我想用C#处理十进制货币(EUR)的价格而不用担心舍入错误而不用我自己的方式进行十进制算术.
The C# reference for the
decimal
type说
Compared to floating-point types,the decimal type has more precision and a smaller range,which makes it appropriate for financial and monetary calculations.
什么?
我不会对精确度有所了解,我只想要七个sig-figs.但我想知道5.31欧元是一个确切的值. A,二进制编码的十进制类型是理想的.所以我的问题是C#decimal是否是那种类型.
不,它不是
BCD(每个数字按特定的位数单独编码) – 但你不希望它. (我当然从未声称它是.)
decimal是一个浮点类型,因为它有一个有效数和一个指数,两个整数 – 它与float和double不同,由指数移位的“点”是小数点而不是二进制点.不幸的是MSDN说“与浮点类型相比”,当它真正意味着“与二进制浮点类型相比”时.
尽管如此,decimal
documentation确实让它变得相当清楚:
A decimal number is a floating-point value that consists of a sign,a numeric value where each digit in the value ranges from 0 to 9,and a scaling factor that indicates the position of a floating decimal point that separates the integral and fractional parts of the numeric value.
The binary representation of a Decimal value consists of a 1-bit sign,a 96-bit integer number,and a scaling factor used to divide the 96-bit integer and specify what portion of it is a decimal fraction. The scaling factor is implicitly the number 10,raised to an exponent ranging from 0 to 28. Therefore,the binary representation of a Decimal value the form,((-296 to 296) / 10(0 to 28)),where -(296-1) is equal to MinValue,and 296-1 is equal to MaxValue. For more information about the binary representation of Decimal values and an example,see the Decimal(Int32[]) constructor and the GetBits method.