Php equation: variable minus same rounded variable, possible? - php

I need to echo number(variable) in two ways and i need help with code for this equation.
Example:
Variable is 5003
First echo has to be: 5000 (rounded)
Second echo has to be just the rounded digits: 3
So i want to know if and how can i achieve this equation, im thinking among lines of: variable(5003) minus rounded variable(5000) equals 3
So that way if variable is lets say 15009
Fist will be 15000
Second will be 9
I hope this make sense, thank you for help

You should look into the roundPHP function:
You can have negative decimal points like this:
round(5003, -3); // returns 5000
round(15009, -3); // returns 15000
To figure out the difference you can do like this:
$input = 5003
$x = $input;
$y = round($input, -3);
$z = $x - $y; // z is now 3
PHP is not a mathematical language, so it cannot solve equations for you.
You can make a more general solution like this:
$inputs = [
5003,
15009,
55108,
102010
];
foreach ($inputs as $input) {
$decimals = floor(log10($input)) - 1;
$rounded = round($input, -1 * $decimals);
echo "$input - $rounded = " . ($input - $rounded) . PHP_EOL;
}
Outputs:
5003 - 5000 = 3
15009 - 15000 = 9
55108 - 55000 = 108
102010 - 100000 = 2010

Assuming that you want to round the last three digits:
$input = 5003;
$rounded = (int)(5003 / 1000) * 1000;
$rest = $input - $rounded;
echo($rounded . "\n" . $rest);
This results in:
5000
3

Related

Round up decimal number for specific decimal places in PHP

I want to round up my variable if it's decimal larger than .3 and if it's lower or equal it will round down, for example if i have 1.34 it will round up to 2, if i have 1.29 it will round down to 1, and if i have 1.3 it will round down to 1. I don't know how to do this precisely, right now i'm using the round basic function like this:
$weight = $weight/1000;
if($weight < 1) $weight = 1;
else $weight = round($weight, 0, PHP_ROUND_HALF_DOWN);
If you manipulate the numbers a bit, you can figure out if the decimals are .3 or higher. You achieve this by flooring the value, and subtract that from the original value. Check if the result of that, multiplied by 10, is greater than 3. If it is, you've got something above x.3.
$number = 1.31;
$int = floor($number);
$float = $number-$int;
if ($float*10 > 3.1)
$result = ceil($number);
else
$result = $int;
echo $result; // 2
Live demo
I made you a little hack, here's the code
$weight = 5088;
$weight = $weight/1000;
if($weight < 1) {
$weight = 1;
} else {
// I get the last number (I treat the $weight as a string here)
$last_number = substr($weight, -1, 1);
// Then I get the precision (floating numbers)
$precision = strlen(substr(strrchr($weight, "."), 1));
// Then I convert it to a string so I can use some helpful string functions
$weight_str = (string) $weight;
// If the last number is less then 3
if ($last_number > 3)
// I change it to 9 I could just change it to 5 and it would work
// because round will round up if then number is 5 or greater
$weight_str[strlen($weight_str) -1] = 9;
}
}
// Then the round will round up if it's 9 or round down if it's 3 or less
$weight = round($weight_str, $precision);
echo $weight;
Maybe something like this function?
function roundImproved($value, $decimalBreakPart = 0.3) {
$whole = floor($value);
$decimal = $value - $whole;
$decimalPartLen = strlen($decimal) - 2;
return (number_format($decimal, $decimalPartLen) <= number_format($decimalBreakPart, $decimalPartLen) ? $whole : ceil($value));
}
Proof:
http://sandbox.onlinephpfunctions.com/code/d75858f175dd819de069a8a05611ac9e7053f07a
You can specify "break part" if you want.

How to make a digit round?

I want 3000 for all these numbers:
3001 - 3500 - 3999
I want 40000 for all these numbers:
40000.3 - 40101 - 48000.8 - 49901
I want 20 for all these numbers:
21 - 25.2 - 29
There is two PHP function to make a digit round (floor and round) But none of them don't act exactly what I need.
Note: I don't know my number is contains how many digits. If fact it is changing.
Is there any approach to do that?
There are "many" ways how to achieve this. One is this:
<?php
echo roundNumber( 29 )."<br>";
echo roundNumber( 590 )."<br>";
echo roundNumber( 3670 )."<br>";
echo roundNumber( 49589 )."<br>";
function roundNumber( $number )
{
$digitCount = floor( log10( $number ) ) ;
$base10 = pow( 10, $digitCount );
return floor( $number / $base10 ) * $base10;
}
?>
The output is this:
20
500
3000
40000
This will work for any no. of digits. Try this:
$input = 25.45;
if (strpos($input, ".") !== FALSE) {
$num = explode('.', $input);
$len = strlen($num[0]);
$input = $num[0];
} else {
$len = strlen($input);
}
$nearest_zeroes = str_repeat("0", $len-1);
$nearest_round = '1'.$nearest_zeroes;
echo floor($input/$nearest_round) * $nearest_round;
The idea is when you round a 4 digit no, say 3999, $nearest_round should be 1000.
For 39990(5 digit), $nearest_round = 10000.
For 25(2 digit), $nearest_round = 10.
And so on.
So, the idea is to generate $nearest_round dynamically based on the no. of digits of $input.
Hope this helps.

PHP - Get length of digits in a number

I would like to ask how I can get the length of digits in an Integer. For example:
$num = 245354;
$numlength = mb_strlen($num);
$numlength should be 6 in this example. Somehow I can't manage it to work?
Thanks
EDIT: The example code above --^ and its respective method mb_strlen(); works just fine.
Maybe:
$num = 245354;
$numlength = strlen((string)$num);
Accepted answer won't work with the big numbers. The better way to calculate the length of any number is to invoke floor(log10($num) + 1) with a check for 0.
$num = 12357;
echo $num !== 0 ? floor(log10($num) + 1) : 1; // prints 5
It has multiple advantages. It's faster, you don't do the casting of types, it works on big numbers, it works with different number systems like bin, hex, oct.
The equation does the logarithm with base 10 then makes the floor of it and adds 1.
This solution can work independently on the base, so if you want to calculate the length of binary or hex just change the base of the logarithm.
Working fiddle
The accepted solution presents a problem when evaluating negative numbers.
It works with a positive number:
$num = 245354;
$numlength = strlen((string)$num);
// Result: 6
But with a negative number, the (-) is added to the count:
$num = -245354;
$numlength = strlen((string)$num);
// Result: 7
Quick workaround:
$num = -245354;
$numlength = strlen((string)abs($num));
// Result: 6
More elegant way :)
ceil(log10($num));
You could also use some basic math!
$digits = (int)(log($num,10)+1)
<?php
$num = 123;
$num2 = 1234;
$num3 = 12345;
function digits($num){
return (int) (log($num, 10) + 1);
}
echo "\n $num: " . digits($num); // 123: 3
echo "\n $num2:" . digits($num2); // 1234: 4
echo "\n $num3:" . digits($num3); // 12345: 5
echo "\n";
Another way to find out the length of a number in digits would be to divide the integer part of the number to 10 until it becomes 0.
Example:
2021/10 = 202.1
202/10 = 20.2
20/10 = 2
2/10 = 0.2
Code:
function numberGetLength($number) {
$count = 0;
while (intval($number) > 0) {
$number = intval($number) / 10;
$count += 1;
}
return $count
}
Just using some version of (int)(log($num,10)+1) fails for 10, 100, 1000, etc. It counts the number 10 as 1 digit, 100 as two digits, etc. It also fails with 0 or any negative number.
If you must use math (and the number is non-negative), use:
$numlength = (int)(log($num+1, 10)+1);
Or for a math solution that counts the digits in positive OR negative numbers:
$numlength = ($num>=0) ? (int)(log($num+1, 10)+1) : (int)(log(1-$num, 10)+1);
But the strlen solution is just about as fast in PHP.
In PHP types are loosely set and guessed, if you want to see something as a string if it is an integer, float, and (i have not tried this) bool then #Gorjunav is the most correct answer.
Reset the variable as a string
$stringNum = (string) $num;
Then you can go anything string related you want with it! And vice-versa for changing a string to an int
$number = (int) $stringNum;
and so on...
count only integer value
`<?php
$n1 =12345;
$n2 =123454.55;
$n3 =12345564.557;
echo "The Number you Type: ".$n1."<br>";
$count = 0;
while ($n1 != 0)
{
$n1 = $n1 / 10;
$n1 = intval($n1);
++$count;
}
echo "The Digit in a Number: ".$count;
}
?>`
echo strlen((string) abs($num)); // using **abs** it'll work with negative integers as well
Tested in PHP 4.4.9 - 8.0.0
$array = array(-1, 0, -0, 1, 4, 9, 10, -10, 20, -20, 100, -100);
foreach( $array as $key => $num ){
echo $key."\t{$num}\t=>\t".($num !== 0 ? floor(log10(abs($num)) + 1) : 1)."\n";
}
/* Output:
0 -1 => 1
1 0 => 1
2 0 => 1
3 1 => 1
4 4 => 1
5 9 => 1
6 10 => 2
7 -10 => 2
8 20 => 2
9 -20 => 2
10 100 => 3
11 -100 => 3
*/
The following function work for either integers or floats (works with PHP7+):
function digitsCount($number): int
{
$number = abs($number);
$numberParts = explode(".", $number);
return
strlen($numberParts[0]) +
(strlen($numberParts[1] ?? 0));
}

PHP Division Float Value WorkAround

Kindly refer: PHP Division Float Value Issue
With reference to the Question I have wrote the following code. Can this be done in different way or less code than this.?
The following will help when any of the two given value are lesser than 1 with decimal values. Is this a good practice?
<?php
$First_Value = 0.005;
$Second_Value = 0.1;
// Check the First Value for Decimal
$First_Whole = floor($First_Value); // 0
$First_Fraction = $First_Value - $First_Whole; // .005
// Check the Second Value for Decimal
$Second_Whole = floor($Second_Value); // 0
$Second_Fraction = $Second_Value - $Second_Whole; // .1
// Multiply with 100 becaus ethe decimal is restricted to 3 digit so multiply with 100 works
if(($First_Whole == 0) || ($Second_Whole == 0)){
$First_Value = $First_Value*100; // 0.5
$Second_Value = $Second_Value*100; // 10
}
echo $tableCount = $Second_Value / $First_Value; // 20
?>
You don't need to do any of that calculation. just do the last division.
...
$value1 = .005;
$value2 = .1;
echo $value1 / $value2;
results in 20
If you are trying to get just 2 decimals you can use number format after dividing. If you are trying to format before dividing then you should still be able to number format. If however, you cannot then why not just multiply both numbers by 1000 (three decimals) % by 1 and minus the difference of the mod from the actual. that will give you 3 in this case, divide back by 1000
[EDIT]
to get the remainder do the following example
...
$v = .0055;
$d = .1;
$a = $d/$v;
$s = $a % ceil($a);
$r = $a - $s;
answer = .18181818181818181...

How to trim leading and trailing zeros in a number in PHP

I have the following numbers:
000000006375 and I want to output 63.75
000000004500 and I want to output just 45
Basically, if the last two numbers are not zero, I wanted to make it a float value wherein a decimal point will be added. But if the last 2 numbers are zeros I just want to output a whole number which in the example is just 45.
I was thinking of casting the numbers to int first but I do not know how to convert it to a float number if there last 2 digits are non-zeros.
You can use this code:
$s = '000000006375';
$i = (int) $s /100; // 63.75
echo "000000006375" / 100;
echo '<br />';
echo "000000004500" / 100;
// Output: 63.75<br />45
For your use case you might just cast it into an integer and divide with 100, like this:
$t1 = "000000006375";
$t2 = "000000004500";
var_dump(myfunc($t1), myfunc($t2));
function myfunc($in) {
$out = (int) $in / 100;
return $out;
}
The output will be something like...
float(63.75)
int(45)
print round('000000006375'/100,2);
print '<br/>';
print round('000000004500'/100,2);
$int = (int)'000000004500';
echo round((substr($int, 0, -2) . '.' . substr($int, -2)),2);
This is one way to do it :)

Categories