PHP float/double stored as MySQL DECIMAL

前端 未结 2 687
温柔的废话
温柔的废话 2021-01-19 18:28

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

相关标签:
2条回答
  • 2021-01-19 18:46

    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.

    0 讨论(0)
  • 2021-01-19 19:01

    Replace the , 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 just inside your query:

    INSERT INTO `random_table_name` SET currency_value = '" . str_replace( ',', '.', $value ) . "'
    
    0 讨论(0)
提交回复
热议问题