mysql余额存浮点数还是int_浮点数-在mysql中存储金额

浮点数-在mysql中存储金额

我想将3.50存储到mysql表中。 我有一个将其存储在其中的浮点数,但它存储为3.5,而不是3.50。 如何获得尾随零?

7个解决方案

94 votes

不要将货币值存储为浮点型,请使用DECIMAL或NUMERIC类型:

MySQL数值类型的文档

编辑和说明:

浮点值容易受到舍入错误的影响,因为它们的精度有限,因此除非您不在乎只得到9.99而不是10.00,否则应使用DECIMAL / NUMERIC,因为它们是不存在此类问题的定点数。

Morfildur answered 2019-10-04T10:51:41Z

36 votes

通常,将货币存储为浮点数不是一个好主意,因为在计算中可能会出现舍入误差。

考虑改用DECIMAL(10,2)。

Andy Joiner answered 2019-10-04T10:52:11Z

19 votes

它存储为3.5、3.50甚至3.500真的重要吗?

真正重要的是从数据库中检索到它后如何显示它。

还是我在这里想念什么?

也不要使用浮点数,请使用小数点。 Float有各种各样的取整问题,并且不是很大。

graham.reeds answered 2019-10-04T10:52:56Z

17 votes

要存储值,可以使用DECIMAL(10,2)字段,然后可以使用FORMAT函数:

SELECT FORMAT(`price`, 2) FROM `table` WHERE 1 = 1

Thiago Belem answered 2019-10-04T10:53:19Z

5 votes

为什么要将“ 3.50”存储到数据库中? 就数据库而言,3.5 == 3.50 == 3.5000。

图形/日期/等的显示和格式设置应在应用程序中完成,而不是在数据库中完成。

Andy Shellam answered 2019-10-04T10:53:49Z

5 votes

如果使用DECIMAL或NUMERIC类型,则可以将它们声明为例如DECIMAL(18,2),即使它们为0,也将强制使用2个小数。根据您期望的值大小,您可以更改第一个参数的值。

MatsT answered 2019-10-04T10:54:13Z

0 votes

二进制不能仅用有限的位数来精确表示浮点数。 它不是那么多的数据丢失,而是实际的转换错误。这是示例手册

您可以在浏览器中看到此操作,并在此代码段中亲自查看。

var floatSum = 0;

// add 0.1 to floatSum 10 times

for (var i=0; i<10; i++) {

floatSum += 0.1;

}

// if the repetative adding was correct, the floatSum should be equal to 1

var expectedSum = 10*0.1; // 1

// you can see that floatSum does not equal 1 because of floating point error

document.write(expectedSum + " == " + floatSum + " = " + (expectedSum==floatSum) + "
");

// --- using integers instead ---

// Assume the example above is adding £0.10 ten times to make £1.00

// With integers, we will use store money in pence (100 pence (also written 100p) in £1)

var intSum = 0;

// add 0.1 to floatSum 10 times

for (var i=0; i<10; i++) {

intSum += 10;

}

// if the repetative adding was correct, the floatSum should be equal to 1

var expectedSum = 10*10; // 100

// you can see that floatSum does not equal 1 because of floating point error

document.write(expectedSum + " == " + intSum + " = " + (expectedSum==intSum) + "
");

document.write("To display as £ instead of pence, we can divide by 100 (presentation only) : £" + intSum/100 + "
");

SnellyCat answered 2019-10-04T10:54:51Z

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值