douzhiling3166 2013-01-21 08:22 采纳率: 100%
浏览 68
已采纳

PHP float / double存储为MySQL DECIMAL

i ran into a really strange problem with storing values in MySQL. The premise:

I have a table that uses DECIMAL(15,8) to store monetary values (like the total of order), but when i try to insert for example:

2,45545345

this is stored as

2.00000000

I tried MySQL's FORMAT/CAST functions but still the same output.

This is how the query gets generated:

$db->query("INSERT INTO `random_table_name` SET currency_value = '" . floatval($value) . "'");

i also tried doubleval, but same result. The funny thing is though that this same piece of code was working fine a couple of weeks ago and i can't recall any changes to the db structure or the db class that can cause this.

  • 写回答

2条回答 默认 最新

  • dooso0594 2013-01-21 08:25
    关注

    Use number_format to replace the , with .

    Like this:

    number_format($value, 8, '.') // 8 = number of decimals, . = decimal separator
    

    However, your problem seems to be related to the current locale. You need to look into the following: setlocale() and localeconv

    setlocale(LC_ALL, 'en_US'); // NOT TESTED, read up on the appropriate syntax
    

    This is the appropriate way of doing this, the alternative would be (as suggested below), to do a str_replace(',', '.'), but you have to do the reverse every time you want to output strings.

    There is another option though, you can set the MySQL locale to en_US.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用