PHP钱字符串转换为整数错误 [英] PHP money string conversion to integer error

查看:177
本文介绍了PHP钱字符串转换为整数错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个小的财务应用程序,PHP作为前端,MySQL作为后端。我有古老的偏见,我在MySQL中存储货币值作为整数分。我的HTML表单允许输入美元值,例如156.64,我使用PHP将其转换为美分,然后将美分存储在数据库中。

I have a small financial application with PHP as the front end and MySQL as the back end. I have ancient prejudices, and I store money values in MySQL as an integer of cents. My HTML forms allow input of dollar values, like "156.64" and I use PHP to convert that to cents and then I store the cents in the database.

函数,它从表单中清除美元值,并将其转换为美分。我剥离前导文本,我剥离尾随文本,我乘以100,并转换为一个整数。最后一步是

I have a function that both cleans the dollar value from the form, and converts it to cents. I strip leading text, I strip trailing text, I multiply by 100 and convert to an integer. That final step is

$ cents =(整数)($ dollars * 100);

这几乎适用于所有的东西,除了很少的值,如'156.64',它一贯转换为15663美分。为什么这样做?

This works fine for almost everything, except for a very few values like '156.64' which consistently converts to 15663 cents. Why does it do this?

如果我这样做:

$ cents = (整数)($ dollars * 100 + 0.5);

为什么我需要添加该舍入值?

then it consistently works. Why do I need to add that rounding value?

此外,我对存储货币金额为整数而不是浮点值的偏见是不再需要?现代浮动计算产生的圆角和准确的货币值是否足以保持100%准确的会计?

Also, my prejudices about storing money amounts as integers and not floating point values, is that no longer needed? Will modern float calculations produce nicely rounded and accurate money values adequate for keeping 100% accurate accounting?

推荐答案

应使用 DECIMAL 数据类型存储您的金额值在MySQL中。

If you want precision, you should store your money values using the DECIMAL data type in MySQL.

这篇关于PHP钱字符串转换为整数错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆