本文介绍了PHP float / double存储为MySQL DECIMAL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个奇怪的问题,在MySQL中存储值。前提是:

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

我有一个表使用 DECIMAL(15,8)来存储货币值但是当我尝试插入例如:

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

这是存储为

2.00000000

我尝试了MySQL的FORMAT / CAST函数,但输出仍然相同。

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

这是查询生成的方式:

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

我也尝试过 doubleval 。有趣的是,虽然同一块代码在几个星期前工作正常,我不记得数据库结构或数据库类可以导致这种情况的任何更改。

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.

推荐答案

使用用替换

Use number_format to replace the , with .

Like this:

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

这是正确的做法, (如下面的建议),做一个 str_replace(',','。'),但你必须反向每次你想输出字符串。

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.

还有另一个选项,可以将MySQL语言环境设置为 en_US

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

这篇关于PHP float / double存储为MySQL DECIMAL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 08:26