php mysql小数0.01_PHP MYSQL saving float in database 0.01?

本文探讨了在MySQL中使用浮点数类型存储货币值遇到的问题,并提供了将数据类型更改为decimal的解决方案,以确保精确存储。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

可以将文章内容翻译成中文,广告屏蔽插件会导致该功能失效:

问题:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值