Home  >  Article  >  Backend Development  >  PHP processing amount (code example)

PHP processing amount (code example)

PHPz
PHPzOriginal
2016-07-20 11:07:391422browse

Code involving amount must be handled with caution. I happened to have a related function recently, so I’ll briefly talk about it below. [Recommended tutorial: php video tutorial]

PHP processing amount (code example)

PHP’s floating point numbers cannot be calculated accurately. You can read this article for details. Fortunately, amounts generally don't have too many decimal places. So when it comes to storage, in a nutshell, it is stored in units of minutes. In MySQL, just store it in int type (select the field type as appropriate).

Calculation:

It is mentioned above that storage is in cents, that is, 1 yuan is stored as 100 cents. You can use PHP's built-in BC Math series of functions for calculations. I will write another detailed explanation in the future.

Format amount

The following is an example of formatting amount

/**
* 格式化金额
* @param $price
* @return string
*/
public function formatPrice($price)
{
if (!is_numeric($price)) {
$price = 0;
}
return number_format(bcdiv($price, 100, 2), 2);
}


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn