65

我想将 3.50 存储到 mysql 表中。我有一个存储它的浮点数,但它存储为 3.5,而不是 3.50。我怎样才能让它有尾随零?

4

7 回答 7

101

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

MySQL 数值类型的文档

编辑和澄清:

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

于 2010-02-12T11:07:52.897 回答
38

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

考虑改用 DECIMAL(10,2)。

于 2010-02-12T12:35:12.820 回答
20

它存储为 3.5、3.50 还是 3.500 真的很重要吗?

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

或者我在这里错过了什么?

也不要使用浮点数,使用小数。Float 有各种舍入问题,而且不是很大。

于 2010-02-12T11:06:33.010 回答
18

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

SELECT FORMAT(`price`, 2) FROM `table` WHERE 1 = 1
于 2010-02-12T11:09:56.403 回答
5

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

您的数字/日期/等的呈现和格式应该在应用程序中完成,而不是在数据库中。

于 2010-02-12T11:08:29.943 回答
5

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

于 2010-02-12T11:09:39.770 回答
1

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

您可以在浏览器中看到这一点,在此代码片段中亲自查看。

<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>

于 2017-06-25T03:02:59.883 回答