在 postgresql 中限制双精度或 float8 类型的十进制数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11113306/
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
Limit decimal digits in Double Precision or float8 type in postgresql
提问by saurjk
I have a postgresql database and am using it for a project which handles monetary value. My question is: How do I limit the number of decimal digits to two for a Double Precision or float8 type column in a postgresql table?
我有一个 postgresql 数据库,正在将它用于处理货币价值的项目。我的问题是:如何将 postgresql 表中双精度或 float8 类型列的小数位数限制为两位?
回答by Sorrow
Simply use Decimal
(Numeric
) type instead, as documented in the manual, e.g. cost decimal(10,2)
.
只需使用Decimal
( Numeric
) 类型代替,如手册中所述,例如cost decimal(10,2)
.
The first number (10) defines the total lengthof the number (all digits, including those after the decimal point), while the second number (2) tells how many of them are after the decimal point. The above declaration gives you 8 digits in front of the point. Of course, you can increase that - the limitations of the Numeric
type are much, much higher.
第一个数字 (10) 定义了数字的总长度(所有数字,包括小数点后的数字),而第二个数字 (2) 表示小数点后有多少个数字。上面的声明为您提供了点前的 8 位数字。当然,您可以增加它 -Numeric
类型的限制要高得多。
In my opinion there is no need to use floating point when you handle currencies or other monetary-related values. I have no idea about the performance comparison between the two types, but Decimal
has one advantage - it is an exact number (which usually is not the case with floating point). I also suggest to read an interesting, but short discussion on the topic.
在我看来,当您处理货币或其他与货币相关的值时,不需要使用浮点数。我不知道这两种类型之间的性能比较,但Decimal
有一个优点 - 它是一个确切的数字(浮点数通常不是这种情况)。我还建议阅读有关该主题的有趣但简短的讨论。