How to handle amounts in PHP

藏色散人
Release: 2023-04-07 20:58:01
forward
4236 people have browsed it

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);
    }
Copy after login

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!

Related labels:
php
source:segmentfault.com
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template