【问题标题】:Format float to be inserted into MySQL decimal(6,5) field要插入 MySQL 十进制(6,5)字段的浮点格式
【发布时间】:2012-02-16 12:15:32
【问题描述】:

我需要在 PHP 中格式化一个浮点数,以便可以将其插入到十进制(6,5)类型的表中的列中。

所以,

20 将格式化为 20.00000

20.5 将被格式化为 20.50000

如何在 PHP 中做到这一点?

【问题讨论】:

  • 你根本不需要格式化...
  • 仅供参考,您不能将20 存储在DECIMAL(6,5) 类型的列中——SQL Error (1264): Out of range value
  • 你想要的可能是decimal(11,5)

标签: php mysql


【解决方案1】:

为避免浮点固有精度误差, 首先转换为十进制(9,2),然后转换为十进制(6,5)。

【讨论】:

    【解决方案2】:

    要格式化数字,只需使用

    <?php
    echo number_format(20, 5); //returns 20.00000
    echo number_format(20.5, 5); //returns 20.50000
    ?>
    

    但您不需要这样做来插入 MySQL 数据库。

    【讨论】:

    • 小心number_format,这里给出的可能会插入千位分隔符!见number_format
    • 第二个参数是十进制:string number_format ( float $number [, int $decimals = 0 ] )我错了吗?
    • @bart 是的,要非常小心 - 我刚刚遇到了这个错误,当时数据库中出现了不同的数字......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多