如何在PHP和MySQL中使用货币值?

如何在PHP和MySQL中使用货币值?

问题描述:

Now I store balance field in MySQL like decimial(15, 2). And in PHP I use the bcmath library for operations:

bccomp($currentBalance, 100.15, 2) - for check if user have enough money. bcadd($currentBalance, 100) - for increase user balance.

And etc.

This is working correctly, but BCMath doc says:

Passing values of type float to a BCMath function which expects a string as operand may not have the desired effect due to the way PHP converts float values to string, namely that the string may be in exponential notation (what is not supported by BCMath), and that the decimal separator is locale dependend (while BCMath always expects a decimal point).

So I want to avoid surprises. What is the right way to deal with money?

现在我将 balance code>字段存储在MySQL中,如 decimial(15,2) 代码>。 在PHP中,我使用 bcmath 库进行操作: p> \ n

bccomp($ currentBalance,100.15,2) code> - 用于检查用户是否有足够的钱。 bcadd($ currentBalance,100) code> - 用于增加 用户余额。 p>

等等。 p>

这是正常的,但BCMath doc说: p>

\ n

将float类型的值传递给BCMath函数,该函数需要将 字符串作为操作数,因为PHP 将浮点值转换为字符串的方式可能不具有所需的效果,即该字符串可能位于 指数中 符号(BCMath不支持的内容), 十进制分隔符是locale dependend(而BCMath总是需要一个 小数点)。 p> blockquote>

所以 我想避免意外。 处理钱的正确方法是什么? p> div>

As integers. Convert 100.15 to 10015 and keep track of the currency so you know how many decimal places to apply when displaying.

Follow http://php.net/manual/en/function.bcadd.php and http://php.net/manual/en/function.bccomp.php

I think you should pass params as string. In your case, maybe bccomp("$currentBalance", "100.15", 2) -> Not yet test.