1

i am trying to save number of cents in MySql table as float , but the database is taking it wrong , for example i am saving 0.01, its saved as 0.1 !

is it possible to make this happen ?

My Code ;

$return["reward"] = 0.05;

$api->user['balance']  += $return["reward"];

$q = $api->pdo->prepare("UPDATE " . DB_PREFIX . "user
                         SET 
                         balance = :balance
                         WHERE 
                         userid = :userid");

$q->bindParam(":balance" , $api->user['balance']  , PDO::PARAM_INT );
$q->bindParam(":userid" , $api->user['userid'] , PDO::PARAM_INT); 

the balance column TYPE float in database.

Kodr.F
  • 13,932
  • 13
  • 46
  • 91

3 Answers3

1

Try with PDO::PARAM_STR instead of PDO::PARAM_INT.

$q->bindParam(":balance" , $return["reward"]  , PDO::PARAM_STR);

From Documentation

MySQL permits a nonstandard syntax: FLOAT(M,D) or REAL(M,D) or DOUBLE PRECISION(M,D). Here, (M,D) means than values can be stored with up to M digits in total, of which D digits may be after the decimal point. For example, a column defined as FLOAT(7,4) will look like -999.9999 when displayed. MySQL performs rounding when storing values, so if you insert 999.00009 into a FLOAT(7,4) column, the approximate result is 999.0001

Also see : https://dev.mysql.com/doc/refman/5.5/en/problems-with-float.html

A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103
1

Try to change column type to decimal and set Length to 7.2 . Which will be seven numbers before the dot and 2 after it

A.Nikolov
  • 23
  • 5
1

This fault is not related to your code.

You're using the data type float which shouldn't be used to store monetary values.

Change your data type to decimal which is considered the best practise for storing monetary values.

You can change it through the webinterface of phpMyAdmin or with a query like so:

ALTER TABLE tablename MODIFY columnname DECIMAL(5,2);

This will allow you to store 5 digits before the comma and 2 after, change it to your needs.

rpm192
  • 2,630
  • 3
  • 20
  • 38
  • Your description of the digits before the comma is incorrect. DECIMAL(5,2) has a total number of digits of 5, with 2 for after the decimal point. https://dev.mysql.com/doc/refman/5.7/en/precision-math-decimal-characteristics.html – profm2 Nov 10 '20 at 15:59