Home >Backend Development >PHP Tutorial >How to handle amounts in PHP
Introduction
Codes involving amounts must be handled with caution. I happened to have a related function recently, so I’ll briefly talk about it below.
Storage
PHP’s floating point numbers cannot be calculated accurately. For details, please see "Things you should know about PHP floating point numbers" This article. 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, it is enough to store it in int type (select the field type as appropriate).
Calculation
It is mentioned above that storage is in units of 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); }
The above is the detailed content of How to handle amounts in PHP. For more information, please follow other related articles on the PHP Chinese website!