可以将文章内容翻译成中文,广告屏蔽插件会导致该功能失效:
问题:
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.
回答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.
回答2:
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
回答3:
Try with PDO::PARAM_STR instead of PDO::PARAM_INT.
$q->bindParam(":balance" , $return["reward"] , PDO::PARAM_STR);
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