我应该使用什么数据类型来表示 C# 中的钱?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1008826/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What data type should I use to represent money in C#?
提问by A Salcedo
In C#, what data type should I use to represent monetary amounts? Decimal? Float? Double? I want to take in consideration: precision, rounding, etc.
在 C# 中,我应该使用什么数据类型来表示货币金额?十进制?漂浮?双倍的?我想考虑:精度、四舍五入等。
采纳答案by Andrew Hare
Use System.Decimal
:
The Decimal value type represents decimal numbers ranging from positive 79,228,162,514,264,337,593,543,950,335 to negative 79,228,162,514,264,337,593,543,950,335. The Decimal value type is appropriate for financial calculations requiring large numbers of significant integral and fractional digits and no round-off errors.The Decimal type does not eliminate the need for rounding. Rather, it minimizes errors due to rounding.
Decimal 值类型表示从正 79,228,162,514,264,337,593,543,950,335 到负 79,228,162,514,264,337,593,543,950,335 的十进制数。 Decimal 值类型适用于需要大量有效整数和小数位且没有舍入错误的财务计算。Decimal 类型不会消除舍入的需要。相反,它最大限度地减少了由于舍入而导致的错误。
Neither System.Single
(float
)nor System.Double
(double
)are precise enoughcapable of representing high-precision floating point numbers without rounding errors.
既不System.Single
(float
)也不System.Double
(double
)是足够精确能够表示没有舍入误差的高精度浮点数。
回答by Fiur
Use decimal and money in the DB if you're using SQL.
如果您使用 SQL,请在数据库中使用小数和货币。
回答by cabgef
In C#, the Decimal type actually a struct with overloaded functions for all math and comparison operations in base 10, so it will have less significant rounding errors. A float (and double), on the other hand is akin to scientific notation in binary. As a result, Decimal types are more accurate when you know the precision you need.
在 C# 中,Decimal 类型实际上是一个带有重载函数的结构体,用于基数为 10 的所有数学和比较运算,因此它的舍入误差较小。另一方面,浮点数(和双精度数)类似于二进制的科学记数法。因此,当您知道所需的精度时,Decimal 类型会更准确。
Run this to see the difference in the accuracy of the 2:
运行此命令以查看 2 的准确度差异:
using System;
using System.Collections.Generic;
using System.Text;
namespace FloatVsDecimal
{
class Program
{
static void Main(string[] args)
{
Decimal _decimal = 1.0m;
float _float = 1.0f;
for (int _i = 0; _i < 5; _i++)
{
Console.WriteLine("float: {0}, decimal: {1}",
_float.ToString("e10"),
_decimal.ToString("e10"));
_decimal += 0.1m;
_float += 0.1f;
}
Console.ReadKey();
}
}
}
回答by Mark Menchavez
Consider using the Money Type for the CLR. It is a custom value type (struct) that also supports currencies and handles rounding off issues.
回答by Debendra Dash
In C# You should take "Decimal" to represent monetary amounts.
在 C# 中,您应该使用“十进制”来表示货币金额。