PHP: Percentage of a number - php

I could never think it would be even challenging but is there any function to calculate a percentage of a number or do I have to write a custom function?
Example:
$result=percent(25,100); //doing the 100%25 operation
$result = 4

function percentage($part, $whole = 100) {
settype($part, "float");
settype($whole, "float");
$formule = ($part / $whole) * 100;
return $formule . " %";
}
echo percentage(25); // returns 25 %
echo percentage(91.8, 176); // returns 52,15909090909091 %
Voila ;-) Could be improved more, but i saw that you figured it out for yourself, so not needed anymore..

Related

Making a function with adding up the numbers between a set of numbers

I have to make a function that works like this:
telOp(2, 5) => 2 + 3 + 4 + 5 = 14
Or
telOp(1, 6) => 1 + 2 + 3 + 4 + 5 + 6 = 21
I have tried a few things but I can't seem to figure it out. I tried making a while loop in the function:
<?php
function telOp($getal1, $getal2){
while ($getal1 <= $getal2){
echo $getal1++;
}
}
$resultaat = telOp(5, 10);
print ($resultaat);
Now this will print the numbers from 5 through 10 but I can't seem to make it work that they add up.
I have also tried simply adding the numbers up with a return statement but combining the 2 doesn't seem to work.:
<?php
function telOp($getal1, $getal2){
while ($getal1 <= $getal2){
echo $getal1++;
}
$resultaat = ($getal1 + $getal2);
return $resultaat;
}
$resultaat = telOp(5, 10);
print ($resultaat);
I am new to php so any tips would also be appreciated!
Problem is that you are adding the numbers outside of the while loop. Also you shouldn't add the upper bound always. Here's the fixed code.
<?php
function telOp($getal1, $getal2){
$resultaat=0;
while ($getal1 <= $getal2){
$resultaat = ($resultaat+ $getal1);
$getal1++;
}
return $resultaat;
}
$resultaat = telOp(5, 10);
print ($resultaat);
Also, here's a small hint to making this run way faster. in order to achieve what you are trying, you don't need to iterate through all the numbers, you can just use a math formula that says that the sum of the first n numbers is n*(n+1)/2. So essentially if you have two numbers a and b, and want to compute a+(a+1)+...+(b-1)+b, you can just compute the sum of the first b numbers with that formula, and subtract the sum of the first a-1 numbers.
You are fairly close. You need to add the numbers up in the telOp function. That can be done in the following way:
<?php
function telOp($getal1, $getal2){
$result = 0;
while ($getal1 <= $getal2){
$result += $getal1++;
}
return $result;
}
$resultaat = telOp(5, 10);
echo ($resultaat);

Is there a specific function that allows me to round up to a specific decimal number in PHP

I have a number that needs to be rounded up to a specific decimal, is there any function in PHP to do that?
I need every number (which reflects an amount of money) to have a specific decimal number.
For example:
The decimal needs to be 25, so if I got $ 25.50 I need it to be $ 26.25, and if I got $ 25.10 it needs to be $ 25.25.
I've checked PHP round(), and specifically ceil(), and I've come across this answer in Python, but I'm not sure it applies to my case, because what I need is different.
Any ideas? Even pseudo code as a tip on where to start will help me. Thanks!
I think you need a custom function, something like this:
function my_round($number, $decimal = 0.25) {
$result = floor($number) + $decimal;
if ($result < $number) $result = ceil($number) + $decimal;
return $result;
}
print my_round(25.50);
I modified this answer for your case:
<?php
function roundUp($number){
$int = floor($number);
$float = $number-$int;
if ($float*10 < 2.5)
$result = $int;
else
$result = ceil($number);
$result+= 0.25;
echo $number." becomes ".$result."\n";
}
roundUp(25.50);
roundUp(25.10);
Look for demo here
Following axiac's advice mentioned in the comments and following this thread, the best way to deal with floating point numbers in the context of currencies, is to treat the dollars and cents' values as 2 separate entities.
One way I can think of it to split the numbers before and after the decimal into 2 separate variables and process accordingly.
<?php
function customRound($amount){
$amount = strval($amount);
if(preg_match('/(\d+)\.?(\d{1,2})?/', $amount, $matches) !== 1){
throw new \Exception("Invalid amount.");
}
$dollars = intval($matches[1]);
$cents = intval($matches[2] ?? 0);
if($cents < 10) $cents *= 10;
if($cents <= 25) return $dollars . ".25";
return ($dollars + 1) . ".25";
}
$tests = [25.51,25.49,26.25,25.10,25.49];
foreach ($tests as $test){
echo $test," => ",customRound($test),PHP_EOL;
}
Here's another approach:
<?php
function roundUp($number, $decimal=0.25){
$dollars = floor($number);
$cents = $number - $dollars;
if($cents > $decimal) {
++$dollars;
}
return $dollars + $decimal;
}
echo roundUp(25.50).PHP_EOL;
echo roundUp(25.10);

Laravel format to 1 decimal place

#if($user->dettagli->facebook_follower >= 1000 && $user->dettagli->facebook_follower <= 999999)
<?php
echo(round($user->dettagli->facebook_follower, 5,PHP_ROUND_HALF_DOWN) . "K");
?>
{{$user->dettagli->facebook_follower / 1000}} K
#endif
Hi could someone please help me. I am using Laravel and trying to display a users Facebook follower count, but I got a little stuck with something. I am taking their int at for example 1589 followers and trying to return in the blade "1.5k". On screen I return either 1589k with this php call or 1.589k. How do I get that number to one decimal place and become only 1.5k??
thank you!
As per the docs
Returns the rounded value of val to specified precision (number of digits after the decimal point). precision can also be negative or zero (default).
You are specifying a precision of 5. You should change this to 1.
Change your function call to:
echo(round($user->dettagli->facebook_follower, 1, PHP_ROUND_HALF_DOWN) . "K");
EDIT: I mis-read the question. This is a function that should handle numbers into the millions.
You would need to use laravel-twigbridge to make the function available in your templates though.
function pretty_number(int $n): string {
$prettyN = $n;
$suffix = '';
$len = strlen((string) $n);
$suffixes = ['K', 'M'];
foreach ($suffixes as $s) {
if ($n < 1000) {
break;
}
$suffix = $s;
$n = $n / 1000;
$prettyN = number_format($n, 1);
}
return $prettyN . $suffix;
}
echo pretty_number(100); // 100
echo pretty_number(999); // 99
echo pretty_number(1589); // 1.6K
echo pretty_number(1600); // 1.6K
echo pretty_number(1589300); // 1.6M
You can use the NumberFormatter. This can be defined in a global place so you only need to use the third line in your blade view.
$a = new \NumberFormatter("en-US", \NumberFormatter::DECIMAL);
$a->setAttribute(\NumberFormatter::MAX_FRACTION_DIGITS, 1);
echo $a->format($user->dettagli->facebook_follower);

php division results in zero (updated - issue was elsewhere)

UPDATE - the problem was actually completely out of the rounding function. It seems as though $price (used in woo commerce) is a string and for some reason I can't use it in a calculation. If I simply return $price, no problem. All of this was fine when I was simply returning the value of the other function.
function xa_only_sale_price($price, $product)
{
error_log ("price in the beginning is " . $price);
if(!is_cart() && !is_checkout() && !is_ajax()){
if ($product->is_type('simple') || $product->is_type('variation')) {
$price = regularPriceHTML_for_simple_and_variation_product($price, $product);
$val = (float)$price;
error_log( "ceiling = " . ceil($val* 2) / 2); // 0 printed to log
return ceil($val* 2) / 2; this returns 0
// return roundNum(regularPriceHTML_for_simple_and_variation_product($price, $product));
}
}
error_log ("price before call is " . $price); // this returns 0
// return roundNum($price); //this is never in use
}
--------------- original post-----------------------------
I am new to php - thank you for all of the help in advance. I am assuming that this issue has something to do with data types but I haven't been able to figure this one out.
In this example $num is the price of a woocommerce product. If I simply return $num I see the price that I am expecting to see. I am simply trying to round the value in this function (I simplified the function for the sake of the question).
function roundNum($num){
$nearest = 0.50;
return ($num / $nearest) ;
This returns 0 to the browser. However, forcing the value of $num results in a valid calculation and return.
function roundNum($num){
$num = 100.0;
$nearest = 0.50;
return ($num / $nearest) ;
The simplest solution is to typecast your input. A small example in your case is:
function roundNum($num){
$nearest = 0.50;
$result = (float) $num/ (float) $nearest;
return $result;
}
Read more about typecasting here
EDIT:
As it turns out your $num is a string. You can change this to a type float and make your calculations, like so:
$num = "48.2";
$float = (float)$num;
echo ceil($float * 2) / 2;
In this example your number is always rounded up by 0.5, so in this case to 48.5
Demo

Convert Fraction to Percent

In our Learning Management System someone in their infinite wisdom decided to keep non-standardized grades. As a result we have a table similar to this:
Assignment 1 - 100
Assignment 2 - 80
Assignment 3 - 10/20
Assignment 4 - 68
Assignment 5 - 8/10
As you can see we have a mixture of percentages and fractions. What i'd like to do is check if the grade is a fraction i.e. 10/20 and if so convert it out to a percentage. Are there any built in php functions for either action? I was thinking of doing a strpos('/'/, $grade); to check if it was a fraction but is there a cleaner way? Additionally to break up the fraction and convert it to a decimal my initial thought was to explode the fraction grade on a / and do (array[1] * 100) / array[2].
Is there any better solution than the one i am thinking?
if(is_nan($grade)) {
if(strpos('/',$grade) !== false) {
$numbers = explode($grade,'/');
$percent = (((int)$numbers[0] / (int)$numbers[1])*100).'%';
} else {
echo "Not a valid grade!";
}
} else {
$percent = $grade.'%';
}
i believe that should work
dont have to deal with pesky regex either
A quick function which you can just pass the values to:
function normal($number)
{
$parts = explode("/", $number);
return count($parts) > 1 ? ($parts[0] * 100) / $parts[1] : $parts[0];
}
Array index starts at zero, not one.
$array = explode('/', $str, 2);
if (count($array) === 2) {
$grade = sprintf('%.2f', 100 * $array[0] / $array[1]);
} else {
$grade = $str;
}
I'd do it like such:
public function convertFractions($givenValue){
if(strpos($givenValue, "/") !== false){
$strings = explode("/", $givenValue);
return 100 * ($strings[0] / $strings[1]);
} else {
return $givenValue;
}
}
My one caveat would be: I'm not sure if the backslash requires escaping, as I've done here, as I didn't have time to test completely. If not, remove the backslash, and you should get the required values from the function every time.
Oh, thats a nice one, you can do it "easy" via regex:
$lines = array(
"10/20",
"20/10",
"90",
);
foreach($lines as $line){
if(preg_match('#([\d]+)/([\d]+)#',$line,$matches)){
print (($matches[1]*100)/$matches[2])."% ";
}else{
print $line."% ";
}
}
returns 50% 200% 90%

Categories