PHP字符串浮动奇怪

时间:2017-11-03 11:17:45

标签: php string

我不明白结果?! 29.85-3.5527136788005E-15 PHP漏洞?与floatval或cast相同的结果 你能帮助我吗 ?这里的简单示例代码:

<?php 
$new = array('29.85');
$two = array('6.95','9.95','12.95');
$montantTotal = 0 ;
foreach ($two as $lignes) {
    $montantTotal += floatval($lignes);
    }
echo $montantTotal ;
$result = $montantTotal - floatval($new[0]);
echo $result;

2 个答案:

答案 0 :(得分:2)

您可以使用number_format

<强>语法

string number_format ( float $number , int $decimals = 0 , string $dec_point = "." , string $thousands_sep = "," )

示例

    $new = array('29.85');
    $two = array('6.95','9.95','12.95');
    $montantTotal = 0 ;
    foreach ($two as $lignes) {
        $montantTotal += (float)$lignes;
        }
   // echo $montantTotal ; echo "<br>";
    $result = number_format($montantTotal,8,".","") - number_format((float)$new[0],8,".","");
    echo $result;

<强>输出

0

答案 1 :(得分:0)

结果非常小。它使用科学记数法。

changeset: * 0e27e683b 2017-09-26 09:35:16 +0300    SRO\john        : #task #18856