Round Percentages PHP - php

I'm currently dividing two values in order to get the percentage from the actual count and the total count for my application.
I am using the following formula:
echo ($fakecount / $totalcount) * 100;
That is giving me a value like: 79.2312313. I would perefer a value like 79%.
I have tried the following:
echo round($fakecount / $totalcount) * 100;
this doesn't seem to work correctly.
Any suggestions?

You need to multiply by 100 before you round, not after:
echo round($fakecount * 100 / $totalcount);
You are calculating $fakecount / $totalcount, which will be a number between 0 and 1, then you round that, so you get either 0 or 1, then you multiply by 100, giving either 0 or 100 for your percentage.

try,
echo (int)($fakecount * 100 / $totalcount + .5);
This works because adding 0.5 increases the integer part by 1 if the decimal part is >= .5
or,
round ($fakecount * 100 / $totalcount);
Note that, I'm doing the multiplication by 100 before the division to better preserve the precision.

echo intval(($fakecount / $totalcount) * 100);
Or you can use
echo floor(($fakecount / $totalcount) * 100); //Round down
Or
echo ceil(($fakecount / $totalcount) * 100); // Round Up

use the round() function
echo round(($fakecount / $totalcount) * 100);
http://php.net/manual/en/function.round.php
others you can use are
ceil() - Round fractions up
floor() - Round fractions down

Nope...
There is a lot of ways to do it.
$mypercent = ($fakecount / $totalcount) * 100;
Remember.. this will first run what is inside of (xxx) and after will * 100.
After this...
echo round($mypercent);
And you can use a lot of rules on that too if you want...
<i>if ($value < 10) {
$value = floor($value);
} else {
$value = round($value);
}</i>
Dont forget to see that other to commands too, maybe you are going to need it.
ceil() - Round fractions up
floor() - Round fractions down
=)

Related

How to extract the percentage from the array

How to extract the percentage from the array
The result is as follows: 41 - 16 - 8 - 33
Total is 98, not 100
How to make it = 100
$sum = array(500.36,200.32,100.09,400);
$total = array_sum($sum);
foreach($sum as $val){
$st = intval($val / $total * 100 );
echo $st.'<br>';
}
The reason is: precision :)
With intval() you skip the decimals. so 41+16+8+33 is REALLY 98.
If you add them with 2 decimals:
41.66 + 16.68 + 8.33 + 33.31 = 99.98
If you do round() instead of intval() you'll round the values so it'll be more close statistically. you'll get: 42 + 17 + 8 + 33 = 100
BUT! if you want to make sure the sum is 100, than you should pick one number (I suggest the biggest one) to calculate that as: 100 - sum(the rest).
Rounding!
Take the number 500.36;
500.36 / 1200.77 * 100:
41,669928463
Since you're using intval those deciamals are lost, remove intval to keep the decimals, then you'll reach 100 total.
Consider an extra variable to check this;
<?php
$sum = array(500.36,200.32,100.09,400);
$total = array_sum($sum);
$test = 0;
foreach($sum as $val){
$st = $val / $total * 100;
echo $st.'<br>';
$test += $st;
}
echo $test;
41.66992846257
16.682628646618
8.3354847306312
33.311958160181
100
Try it online!
you are using intval(). you should use round() with the precision of 2. you are skipping fractions by converting answer to integer. PHP is using floor method so your answer is losing fractions. here is the code
$sum = array(500.36,200.32,100.09,400);
$total = array_sum($sum);
foreach($sum as $val){
$st = round($val / $total * 100, 2 );
echo $st.'<br>';
}
If you make an intval to the result you cut the last values.
Without intval you can see the problem.
41.66992846257
16.682628646618
8.3354847306312
33.311958160181
So work with that numbers or round it on 2 decimal numbers.
$st = number_format($val / $total * 100, 2, '.', '');
something like this.

How to solve floating 0.01 value on percentage discount

I'm facing some troubles with .01 values at the end of calculation and i would like to ask if someone has passed trough this issue and can give me a hand to solve mine.
I have this situation:
$total = '319.00';
$discount = '99.00';
$percentage_discount = number_format((1+($discount/$total)) * 100 - 100, 2, '.', '');
echo $percentage_discount . " %<br>";
echo $discount . "<br>";
echo number_format($total * (1-($percentage_discount / 100)), 2, '.', ''); //echo total
Result:
31.03 %
99.00
220.01
The result i need is The right percentage to get the final total value with 220.00
I know that on Magento VAT calculation was a problem similar to this, the final decimals floating was an issue from the beginning and hard to solve, but maybe some experienced person has solves this.
Remove number_format() on $persentage_discount, i.e. leave it as is:
$percentage_discount = ((1 + ($discount / $total)) * 100 - 100);
Otherwhise you are making double round during calculations and final result is 220.0143 because of that. If you want to show $persentage_discount somewhere, use printf().
Update: just simplify the task and separate displays from real calculations:
<?php
$total = '319.00';
$discount = '99.00';
$percentage_discount = ($discount / $total) * 100;
$final = $total * (1-($percentage_discount / 100));
printf('%.2f<br>', $total);
printf('%.2f<br>', $discount);
printf('%.2f%%<br>', $percentage_discount);
printf('%.2f<br>', $final);
?>
output:
319.00
99.00
31.03%
220.00
intval() will do the trick. try it and let me know
echo $new=number_format($total * (1-($percentage_discount / 100)), 2, '.', '').""; //echo total
echo intval($new);

PHP round half up doesn't work

I have this code
<?php echo round(0.572,2,PHP_ROUND_HALF_UP);?>
I want to round two decimals to half up, I expect a value as 0.58...
but the above code print 0.57
How can I do this?
if you expect 0,58 you don't have to use a "half round" but the ceil function
$v = 0.575;
echo ceil($v * 100) / 100; // show 0,58
The value 0.572 can not be rounded up to 0.58, because the third decimal, 2, is less than half (or 5). If you were doing round(0.575, 2, PHP_ROUND_HALF_UP) you would get 0.58. In this case 0.57 is the correct rounded value.
If you wish to always round up from the 3rd decimal, regardless of its value you could use ciel() instead, but it requires a little additional math. A simple function to demonstrate rounding up always would be...
function forceRoundUp($value, $decimals)
{
$ord = pow(10, $decimals);
return ceil($value * $ord) / $ord;
}
echo forceRoundUp(0.572, 2); // 0.58
echo forceRoundUp(0.57321, 4); // 0.5733
function round_up($value, $places)
{
$mult = pow(10, abs($places));
return $places < 0 ?
ceil($value / $mult) * $mult :
ceil($value * $mult) / $mult;
}
echo round_up(0.572,2);
Hope this will work for you!!

Set precision for a float number in PHP

I get a number from database and this number might be either float or int.
I need to set the decimal precision of the number to 3, which makes the number not longer than (regarding decimals) 5.020 or 1518845.756.
Using PHP
round($number, $precision)
I see a problem:
It rounds the number. I need a function to only cut the decimals short, without changing their values which round( ) seems not to follow.
You can use number_format() to achieve this:
echo number_format((float) $number, $precision, '.', '');
This would convert 1518845.756789 to 1518845.757.
But if you just want to cut off the number of decimal places short to 3, and not round, then you can do the following:
$number = intval($number * ($p = pow(10, $precision))) / $p;
It may look intimidating at first, but the concept is really simple. You have a number, you multiply it by 103 (it becomes 1518845756.789), cast it to an integer so everything after the 3 decimal places is removed (becomes 1518845756), and then divide the result by 103 (becomes 1518845.756).
Demo
Its sound like floor with decimals. So you can try something like
floor($number*1000)/1000
If I understand correctly, you would not want rounding to occur and you would want the precision to be 3.
So the idea is to use number_format() for a precision of 4 and then remove the last digit:
$number = '1518845.756789';
$precision = 3;
echo substr(number_format($number, $precision+1, '.', ''), 0, -1);
Will display:
1518845.756
rather than:
1518845.757
Links : number_format() , substr()
See this answer for more details.
function numberPrecision($number, $decimals = 0)
{
$negation = ($number < 0) ? (-1) : 1;
$coefficient = pow(10, $decimals);
return $negation * floor((string)(abs($number) * $coefficient)) / $coefficient;
}
$num=5.1239;
$testnum=intval($num*1000)/1000;
echo $testnum; //return 5.123

round number to nearest 0.2 with PHP

I'm creating this rating system using 5-edged stars. And I want the heading to include the average rating. So I've created stars showing 1/5ths. Using "1.2" I'll get a full star and one point on the next star and so on...
But I haven't found a good way to round up to the closest .2... I figured I could multiply by 10, then round of, and then run a switch to round 1 up to 2, 3 up to 4 and so on. But that seems tedious and unnecessary...
round(3.78 * 5) / 5 = 3.8
A flexible solution
function roundToNearestFraction( $number, $fractionAsDecimal )
{
$factor = 1 / $fractionAsDecimal;
return round( $number * $factor ) / $factor;
}
// Round to nearest fifth
echo roundToNearestFraction( 3.78, 1/5 );
// Round to nearest third
echo roundToNearestFraction( 3.78, 1/3 );
function round2($original) {
$times5 = $original * 5;
return round($times5) / 5;
}
So your total is 25, would it be possible to not use floats and use 1->25/25? That way there is less calculations needed... (if any at all)
Why is everyone giving solutions that require a deeper inspection or conversion? Want 0.2? Then:
round($n / 0.2) * 0.2; // $n = 3.78 / 0.2 = 18.9 (=) 19 * 0.2 = 3.8 //
Want 5? Then:
round($n / 5) * 5; // $n = 17 / 5 = 3.4 (=) 3 * 5 = 15 //
It's as simple as that.

Categories