在mysql中存储金额

我想将3.50存储到一个MySQL表中。 我有一个float,我存储它,但它存储为3.5,而不是3.50。 我怎么能得到它的尾部零?

不要将货币值存储为浮点数,请使用DECIMAL或NUMERICtypes:

MySQL数字types的文档

编辑和澄清:

浮点值容易受到舍入误差的影响,因为它们的精度有限,所以除非你不关心只能得到9.99而不是10.00,否则应该使用DECIMAL / NUMERIC,因为它们是没有这种问题的定点数。

将货币存入浮动通常不是一个好主意,因为在计算中可能会发生舍入错误。

考虑使用DECIMAL(10,2)。

它真的很重要,如果它的商店是3.5,3.50甚至3.500?

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

还是我在这里错过了什么?

也不要使用浮点数,使用小数点。 浮动有各种各样的四舍五入问题,并不是很大。

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

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

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

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

您的演示和格式的数字/date/等应在应用程序,而不是数据库。

二进制不能准确地表示只有有限位数的浮点数。 这不是那么多的数据丢失,但实际上是转换错误。 下面是手册给出的例子

你可以在浏览器中看到这个动作,在这个代码片段中看看你自己。

 <script> 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) + "<br />"); // --- 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) + "<br />"); document.write("To display as &pound; instead of pence, we can divide by 100 (presentation only) : &pound;" + intSum/100 + "<br />"); </script>