浮点数-在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