PHP float / double is stored as MySQL DECIMAL

I am having a really strange problem with storing values ​​in MySQL. Package:

I have a table that uses DECIMAL(15,8)

to store monetary values ​​(like the whole order), but when I try to insert like:

2,45545345

      

this is saved as

2.00000000

      

I tried MySQL FORMAT / CAST but still the same result.

This is how the request is generated:

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

      

I have also tried doubleval

but same result. The funny thing is, this same piece of code worked great a couple of weeks ago and I can't remember any changes to the db structure or db class that might cause this.

+3


source to share


2 answers


Use number_format to replace ,

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 a suitable way to do it, an alternative would be (as suggested below) to do it str_replace(',', '.')

, but you must do the opposite every time you want to output lines.

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

.

+7


source


Replace ,

with .

before inserting into db:

$value = str_replace( ',', '.', $value);

      



This will create a valid number that can be safely inserted into the database. Or just add it directly to your request:

INSERT INTO `random_table_name` SET currency_value = '" . str_replace( ',', '.', $value ) . "'

      

+3


source







All Articles