我正在尝试对两个数字进行简单的运算,但该运算返回错误的结果。

例如,数字是 46.2910$a 变量中的第一个和 $b 变量中的第二个。

进程

echo $a * $b


echo 10 * 46.29


$a * 10


46.29 * $b


echo $a


echo $b


echo floatval($a) * floatval($b)


echo intval($a)



我也尝试使用 bcmul ,在这种情况下它会打印 0。

在这里你可以找到我的代码:
include 'simple_html_dom.php';

     $anno = $_POST['Anno'];
     $punti = $_POST['Punti'];
     $eta = $_POST['Eta'];
     $ggAss = $_POST['GgAss'];
     $ggParz1 = $_POST['GgParz1'];
     $ggParz2 = $_POST['GgParz2'];
     $ggParz3 = $_POST['GgParz3'];
     $pctDM = $_POST['PctDM'];
     $calcoloDM = $_POST['CalcoloDannoMorale'];
     $speseMediche = $_POST['SpeseMediche'];
     $spese = $_POST['Spese'];

    $html = file_get_html('..\tabella'.$anno.'.php');

    $rows = $html->find('tr');

    // This variable is use to make sure that the correct number will be display. (there is a kind of offset in the output table).
    $const = 2;


    $i = 0;
    $cond = false;
    foreach ($rows as $row) {
        $j = 0;
        foreach ($row->children() as $cell) {
            if($cond)
                break;
            //This condition is used to get punto base e indennità giornaliera
            if($i == 1) {
                $var1 = explode(" ", $cell->plaintext);
                $indennitaGG = $var1[10]; // here we can get indennità giornaliera
            }
            if($i == ($eta + $const) && $j == $punti) {
                $dannoBP = $cell->plaintext;
                $cond = true;
                break;
            }
            $j++;
        }
        $i++;
    }

    $calcIndGG = $indennitaGG * $ggAss;
    $newVar = $indennittaGG;
    echo 46.29 * 10;
    $calcIndParz1 = ($indennitaGG * 75 / 100) * $ggParz1;
    $calcIndParz2 = ($indennitaGG * 50 / 100) * $ggParz2;
    $calcIndParz3 = ($indennitaGG * 25 / 100) * $ggParz3;
    $dm = ($calcIndGG + $calcIndParz1 + $calcIndParz2 + $calcIndParz3) * $pctDM / 100;

    $totale = $dannoBP + $calcIndGG + $calcIndParz1 + $calcIndParz2 + $calcIndParz3 + $dm + $speseMediche + $spese;

这有什么问题?

编辑:
使用此代码解决的问题:
//This change is used to transform the variable $indennitaGG in the right form. (with the . and not with the ,). Then we can make the cast to float.


    $temp = str_replace(",",".", $indennitaGG);
        $indennitaGG = (float)$temp;

最佳答案

, 字符对浮点数无效。
尝试用 str_replace(",",".",$a); 替换它。如果您愿意,甚至可以尝试同时使用两个数字。

“官方”小数点分隔符(用于 PHP)是一个点( . ),这就是它无法进行乘法的原因。在您的语言中,它可能是逗号,但 PHP 使用点。

这是 PHP 会说的(对 floatval($a) ):



如果您使用此代码,它应该可以工作:

str_replace(",",".",$a);
str_replace(",",".",$b);
echo floatval($a) * floatval($b);

解释:

正如我所说,您使用的是无效的十进制逗号。 str_replace(original, replacement, subject) 的作用是查找字符串中所有出现的 original(此处:subject)并将其替换为替换值。这导致用小数点替换小数点逗号。

示例:40,3 变成 40.3
这仍然导致 String 数据类型,它显然不是数字。为了转换它,我们使用 floatval(string) 方法,它产生一个 Float 数据类型,它是浮点数的缩写,之后我们可以执行算术运算。

关于php - PHP 中的错误乘法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36530695/

10-11 20:11
查看更多