跳至主要內容

PHP 高精度计算

逸尘.Lycodx大约 2 分钟后端PHP

PHP高精度计算

前言

总所周知不管什么语言在计算浮点类型的时候都会出现精度丢失问题,这是由于计算机使用二进制来表示浮点数,而不是十进制,因此可能会导致精度丢失。

PHP中有高精度计算函数帮助我们快速处理这类问题

一、开启扩展

PHP的高精度计算依赖于 bcmath 扩展

1、扩展安装

# Debian/Ubuntu
sudo apt-get install php-bcmath
# CentOS
sudo yum install php-bcmath

2、修改配置文件

php.ini文件中找到;extension=bcmath去除前面的;

二、描述

1、加法

语法:

bcadd(string $num1, string $num2, ?int $scale = null): string

说明

$scale: 此可选参数用于设置结果中小数点后的小数位数。也可通过使用 bcscale()open in new window 来设置全局默认的小数位数,用于所有函数。如果未设置,则默认为 0

示例:

<?php
$num1 = '12345678901234567890';
$num2 = '98765432109876543210';
$sum = bcadd($num1, $num2, 2);
echo $sum; // 输出:111111111111111111100.00

2、减法

语法:

bcsub(string $num1, string $num2, ?int $scale = null): string

说明

$scale: 此可选参数用于设置结果中小数点后的小数位数。也可通过使用 bcscale()open in new window 来设置全局默认的小数位数,用于所有函数。如果未设置,则默认为 0

示例:

<?php
$num1 = '12345678901234567890';
$num2 = '98765432109876543210';
$diff = bcsub($num2, $num1, 2);
echo $diff; // 输出:86419753208641975320.00    

3、乘法

语法:

bcmul(string $num1, string $num2, ?int $scale = null): string

说明

$scale: 此可选参数用于设置结果中小数点后的小数位数。也可通过使用 bcscale()open in new window 来设置全局默认的小数位数,用于所有函数。如果未设置,则默认为 0

示例:

<?php
$num1 = '12345678901234567890';
$num2 = '98765432109876543210';
$product = bcmul($num1, $num2, 2);
echo $product; // 输出:1219326311370217951280560347910410000.00

4、除法

语法:

bcdiv(string $num1, string $num2, ?int $scale = null): string

说明

$scale: 此可选参数用于设置结果中小数点后的小数位数。也可通过使用 bcscale()open in new window 来设置全局默认的小数位数,用于所有函数。如果未设置,则默认为 0

示例:

<?php
$num1 = '12345678901234567890';
$num2 = '98765432109876543210';
$quotient = bcdiv($num1, $num2, 2);
echo $quotient; // 输出:0.12 

注意

1、 这些函数的参数必须是字符串类型,而且计算结果也是字符串类型

2、 在实际使用中,由于高精度计算会消耗更多的系统资源,因此需要注意性能和效率问题

上次编辑于: