在 MySQL 数据库中存储货币值时,哪个数据类型最为合适?


为了表示货币,我们需要使用 Decimal (TotalDigitsinteger, DigitsAfterDecimalinteger) 方法。

比如,我们需要显示 345.66 这个值。这当中有几位数。345.66 中共有 5 位数,小数点后两位,也就是 66。

我们可以借助 MySQL 的 Decimal() 方法来表示同一内容。以下是准确表示方法。

DECIMAL(5,2)

让我们先创建一个表格,并对我们示例中的上述表示法进行考虑 −

mysql> create table MoneyRepresentation
   -> (
   -> Money Decimal(5,2)
   -> );
Query OK, 0 rows affected (0.65 sec)

让我们插入相同的值,即 345.66

mysql> insert into MoneyRepresentation values(345.66);
Query OK, 1 row affected (0.13 sec)

借助 SELECT 语句显示所有记录。查询如下 −

mysql> select *from MoneyRepresentation;

以下是输出结果。

+--------+
| Money  |
+--------+
| 345.66 |
+--------+
1 row in set (0.00 sec)

查看上述输出,我们得到 5 位数总数,并在小数点后添加了 2 位数字,因为我们已将函数设置为

Decimal(5,2)

更新时间: 30-7-2019

656 次浏览

启动你的 职业生涯

完成课程可获得认证

开始
广告
© . All rights reserved.