PHP底片不断添加 [英] PHP negatives keep adding
问题描述
我这里有这个代码......
I have this code here...
$remaining = 0;
foreach($clientArrayInvoice as $key=>$row){
$remaining = $remaining + $row['total'];
}
它做什么,需要总值并将它们加起来.. 。但是当我有值为负数的时候,当我有 -51.75
和 -17.85 $ c时,它也会添加它们。 $ c>我得到
-69.60
它应该是 -33.90
我该如何解决这个问题?
What it does, it takes the values of total and adds them up...but when I have values that are negatives, it adds them up as well for an example when I have -51.75
and -17.85
I get -69.60
which it should be -33.90
how do I fix this?
`-33.901是我期待的值,因为当我想减去它的两个底片时,不要添加
`-33.901 is the value I am expecting because when its two negatives I would like to subtract, not add
谢谢,
J
Thanks, J
推荐答案
这可能有所帮助:
(-51.75) + (-17.85) = -69.60
(-51.75) - (-17.85) = -33.90
假设您总是需要添加第二个数字而不管它的符号,您需要使用 PHP abs
功能,带 $ row ['total']
:
Assuming you always need to add the second number regardless of it's sign, you need to take the absolute value by using the PHP abs
function with $row['total']
:
$remaining = 0;
foreach($clientArrayInvoice as $key=>$row){
$remaining = $remaining + abs($row['total']);
}
回应你的意思在您的问题中更新:
In response to what you updated in your question:
-33.90是我期待的值,因为当它的两个底片我想减去,而不是添加
-33.90 is the value I am expecting because when its two negatives I would like to subtract, not add
这几乎是使用 abs
函数的功能。我可以将上面的代码片段重写为:
This is pretty much what using the abs
function does. I could rewrite the above code snippet as:
$remaining = 0;
foreach($clientArrayInvoice as $key=>$row) {
if ($remaining >= 0) {
$remaining = $remaining + abs($row['total']);
}
else {
$remaining = $remaining - abs($row['total']);
}
}
然而,这与使用简单完全相同PHP abs
函数,因为你总是将 $ row ['total']
的大小添加到 $剩余
。
However, this does the exact same thing as simply using the PHP abs
function, since you are always adding the magnitude of $row['total']
to $remaining
.
这篇关于PHP底片不断添加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!