开发者

PHP: basic percentage calculation [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center. Closed 10 years ago.

I have $sum and need to calculate the sum minus 15% and then I need to display the original value again.

$sum = 199;
echo "value 1: $sum";
开发者_Python百科$sum = $sum*0.85;
echo "value 2: $sum";
$foo = $sum*1.15; 
echo "value 3: $foo";

This is the result I get:

value 1: 199 
value 2: 169.15 
value 3: 194.5225

Please tell a very stupid person why this formula is obviously wrong and doesn't return 199 in the last output.


I agree with everybody about just keeping the original variable. However, the single-variable answer is this:

1.99 * .85 = 169.15
169.15 / .85 = 1.99

Change operator ;)


It's because 1/1.15 is not equal to 0.85.


Basically, you starting off with 199 and finding 85% of that (the subtract 15%) which is correct. But now, when you're trying to gain the 15% back you're doing so based on the value of 15% of 169.15 (25.3725) not 15% of 199 (29.85).

As mentioned in another answer, if you need to original number back, keep it in a variable and use a temp variable to hold the percentage.


$sum = 199;
echo "value 1: $sum<br />";
$sum2 = $sum*0.85;
echo "value 2: $sum2<br />";
echo "value 3: $sum<br />";

So, who's the genius?


Percentages don't work that way. You can't just do the reverse to the result of the first operation. You should just store the original number and use that.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜