Postgres数据类型NUMERIC可以存储带符号的值吗? [英] Can the Postgres data type NUMERIC store signed values?

查看:583
本文介绍了Postgres数据类型NUMERIC可以存储带符号的值吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在PostgreSQL中,我想存储带符号的值 -999.9 - 9999.9
我可以使用数字(5.1)吗?

In PostgreSQL, I would like to store signed values -999.9 - 9999.9. Can I use numeric(5.1) for this?

还是应该使用哪种类型? / p>

Or what type should I use?

推荐答案

您当然可以使用任意精度类型数字 ,精度为5,小数位为1, 就像@Simon注释一样,但没有语法错误。在类型修饰符中使用逗号()代替点():

You can certainly use the arbitrary precision type numeric with a precision of 5 and a scale of 1, just like @Simon commented, but without the syntax error. Use a comma(,) instead of the dot (.) in the type modifier:

SELECT numeric(5,1) '-999.9' AS nr_lower
     , numeric(5,1) '9999.9' AS nr_upper;

 nr_lower | nr_upper
----------+----------
   -999.9 |   9999.9

字符串文字中的减号和小数点不会计入允许的最大有效位数( precision )。

如果不需要限制长度,只需使用数字

如果您需要实施最小值和最大值,请添加检查约束

The minus sign and the dot in the string literal do not count against the allowed maximum of significant digits (precision).
If you don't need to restrict the length, just use numeric.
If you need to enforce minimum and maximum, add a check constraint:

CHECK (nr_column BETWEEN -999.9 AND 9999.9)

数字存储您的电话号码完全。如果您不需要绝对精度并且微小的舍入误差也没有问题,则还可以使用以下浮点类型之一 double precision float8 )或 real float4 )。

numeric stores your number exactly. If you don't need the absolute precision and tiny rounding errors are no problem, you might also use one of the floating point types double precision (float8) or real (float4).

或者,由于您只允许使用一个小数位小数,因此可以乘以10并使用整数,这将是最有效的存储方式:4个字节,没有舍入错误,处理速度最快。只需正确使用并记录该号码即可。

Or, since you only allow a single fractional decimal digit, you can multiply by 10 and use integer, which would be the most efficient storage: 4 bytes, no rounding errors and fastest processing. Just use and document the number properly.

详细信息手册中的数字类型。

这篇关于Postgres数据类型NUMERIC可以存储带符号的值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆