Home > Backend Development > PHP Tutorial > PHP中两个float(浮点数)比较实例分析_PHP

PHP中两个float(浮点数)比较实例分析_PHP

WBOY
Release: 2016-05-29 11:48:09
Original
1082 people have browsed it

本文实例讲述了PHP中两个float(浮点数)比较方法。分享给大家供大家参考。具体如下:

最近在开发一个合同管理系统的时候,涉及到两个浮点数比较,算是把我郁闷惨了。
在N久以前,就不晓得从哪里听来的一个“不要用等号去比较浮点数”的“真理”,自己平时也在用,好像没有出现啥问题,可这次问题总算是来了。

<&#63;php
$sum = "12300.00";
$a  = "10000.30";
$b  = "2000.30";
$c  =  "299.40";
$sum = (float) $sum;
$s = (float) ($a+$b+$c);
var_dump($sum, $s);
var_dump($sum==$s);

Copy after login

结果是:

float(12300)
float(12300)
bool(false)

后来才知道在PHP中,要比较两个浮点数的大小,可以用bccomp(参数1,参数2,小数位)来比较。

<&#63;php
$sum = "12300.00";
$a  = "10000.30";
$b  = "2000.30";
$c  =  "299.40";
$sum = (float) $sum;
$s = (float) ($a+$b+$c);
var_dump($sum, $s);
var_dump(bccomp($sum,$s,2));

Copy after login

结果:

float(12300)
float(12300)
int(0) // 0表示两个浮点数值相等

bccomp函数具体用法可参考PHP手册。

希望本文所述对大家的php程序设计有所帮助。

source:php.cn
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