perform round function without using round() in php [duplicate] - php

This question already has answers here:
Print numeric values to two decimal places
(6 answers)
Closed 11 months ago.
without use of round() function perfrom the round() in php
$a = "123.45785";
$v = round($a);
output: 123.46;
it had done by round function but i want to get output without use of round and number_format() function.

Here's a way of doing it with arithmetics:
function my_round($num, $places = 2) {
// Multiply to "move" decimals to the integer part
// (Save one extra digit for rounding)
$num *= pow(10, $places + 1);
// Truncate to remove decimal part
$num = (int) $num;
// Do rounding based on the last digit
$lastDigit = $num % 10;
if ($lastDigit >= 5)
$num += 10;
// Remove last digit
$num = (int) ($num/10);
// "Move" decimals in place, and you're done
$num /= pow(10, $places);
return $num;
}

You have sprintf.
$a = "123.45785";
echo sprintf("%01.2f", $a); // output: 123.46

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.

Round to Highest Factor with Variable Scale? [duplicate]

This question already has answers here:
Round to max thousand, hundred etc in PHP
(5 answers)
Closed 5 years ago.
PHP's floor() and ceil() is useful for rounding floats to their nearest integers.
But what if we need to find the highest multiple of 10 (hundreds, thousands, etc.) for a given number? For example:
num_to_scale(538.9) // 500
num_to_scale(543123654.01234) // 5000000
Try this code, check the live demo. You also can refer to this post.
$floor = floor($v);
return str_pad(substr($floor, 0, 1), strlen($floor), '0');
function num_to_scale($number) {
$multiple=1; $test=1;
for ($i=1; $test>=1; $i++) {
$factor = $multiple/10;
$test = $number/$multiple;
$multiple = $multiple*10;
$scale = floor($number/$factor)*$factor;
} return $scale;
}
or more simply:
function num_to_scale($n) {
$m=1; $t=1;
for ($i=1; $t>=1; $i++) {
$f=$m/10; $t=$n/$m; $m=$m*10; $s=floor($n/$f)*$f;
} return $s;
}
Combined with a helper function to convert integers to text strings, we can easily do something like this:
echo 'Over '.num_to_scale(5395206).' units sold.';
// Over five million units sold.
try this:
function num_to_scale($number) {
$num = (int) floor($number);
$ln = strlen($num) - 1;
return (int) floor($num / pow(10, $ln)) * pow(10, $ln);
}
My answer uses logarithm :
function num_to_scale($var) {
$nbDigits = (int)log($var,10);
return (int)($var/10**$nbDigits)*10**$nbDigits;
}

Extract one number from another number in PHP [duplicate]

This question already has answers here:
What is the best way to validate a credit card in PHP?
(8 answers)
Closed 7 years ago.
so tonight i was trying to create a function that will check if a credit card is valid or not.
However i'm stuck here.
In my calcul, i get number such as 10, 56, 30... number with 2 numbers.
(I mean, 1 is a number with 1 number just like 2, 3, 4 ,5 6, 7 , 8 ,9.. number with two numbers would be 10 ans higher.)
What I need to do is :
Get the first number and add it to a new variable, and do the same thing with another variable.
Example:
I have this number -> 23
I need to :
$var1 = 2;
$var2 = 3;
I wanted to use the function subtr, but it looks like it doesn't works with numbers ..
Thanks for reading !!
I hope you get something from this. Casting the number into a string first and then split the number using substr() after that cast the splitted value to integer again:
$num = 23;
$str_num = (string)$num;
$var1 = (int)substr($str_num, 0, 1);
$var2 = (int)substr($str_num, 1, 1);
Or using a pure numbers:
$num = 23;
$var2 = $num % 10;
$var1 = ($num - $var2) / 10;
Credit card numbers can be validated using an algorithm called the Luhn Algorithm.
If you need this in a project, don't reinvent the wheel. Check out this project on github.
Here's a way to do this using purely numbers (without ever casting to strings). This'll also work on any length of numbers assigning it to $var1, $var2, ... , $varn for n length number.
$num = 23;
$count = 1;
while ($num > 0) {
$var = "var".$count++;
$$var = $num % 10;
$num = intval($num / 10);
}
a numeric solution
$num = 23;
$var1 = floor($num / 10);
$var2 = $num % 10;
echo "$var1 $var2";

How to find reminder and Quotient in php?

I can find reminder by "%" operator . But how can I find the quotient at the same time . Suppose I will divide 10 by 3 . If there is any function which will give me the output 3 as quotient and 1 as reminder .
$remainder = $a % $b;
$quotient = ($a - $remainder) / $b;
Use type casting:
$quotient = (int)(10/3)
This will divide 10 by 3 and then cast that result to an integer.
Since functions can only return a single value (not counting pass-by-reference functionality), there's no way to return 2 separate values from a single function call (getting both the quotient and remainder at the same time). If you need to calculate two different values, then you will need at least two statements.
You can, however, return an array of values and use PHP's list function to retrieve the results in what looks like a single statement:
function getQuotientAndRemainder($divisor, $dividend) {
$quotient = (int)($divisor / $dividend);
$remainder = $divisor % $dividend;
return array( $quotient, $remainder );
}
list($quotient, $remainder) = getQuotientAndRemainder(10, 3);
How about gmp_div_qr function
<?php
$res = gmp_div_qr(11,5);
die(var_dump($res));
the accepted answer will not work with float values.
another way with inbuilt php>(v.4.2.0) method
fmod
$remainder = fmod ( float $x , float $y );
$quotient = ($x - $remainder) / $y;
Try this
$x=10;
$y=3;
$Quotient =(int)($x/$y);
$Remainder = $x % $y;

How to round down to the nearest significant figure in php

Is there any slick way to round down to the nearest significant figure in php?
So:
0->0
9->9
10->10
17->10
77->70
114->100
745->700
1200->1000
?
$numbers = array(1, 9, 14, 53, 112, 725, 1001, 1200);
foreach($numbers as $number) {
printf('%d => %d'
, $number
, $number - $number % pow(10, floor(log10($number)))
);
echo "\n";
}
Unfortunately this fails horribly when $number is 0, but it does produce the expected result for positive integers. And it is a math-only solution.
Here's a pure math solution. This is also a more flexible solution if you ever wanted to round up or down, and not just down. And it works on 0 :)
if($num === 0) return 0;
$digits = (int)(log10($num));
$num = (pow(10, $digits)) * floor($num/(pow(10, $digits)));
You could replace floor with round or ceil. Actually, if you wanted to round to the nearest, you could simplify the third line even more.
$num = round($num, -$digits);
If you do want to have a mathy solution, try this:
function floorToFirst($int) {
if (0 === $int) return 0;
$nearest = pow(10, floor(log($int, 10)));
return floor($int / $nearest) * $nearest;
}
Something like this:
$str = (string)$value;
echo (int)($str[0] . str_repeat('0', strlen($str) - 1));
It's totally non-mathy, but I would just do this utilizing sting length... there's probably a smoother way to handle it but you could acomplish it with
function significant($number){
$digits = count($number);
if($digits >= 2){
$newNumber = substr($number,0,1);
$digits--;
for($i = 0; $i < $digits; $i++){
$newNumber = $newNumber . "0";
}
}
return $newNumber;
}
A math based alternative:
$mod = pow(10, intval(round(log10($value) - 0.5)));
$answer = ((int)($value / $mod)) * $mod;
I know this is an old thread but I read it when looking for inspiration on how to solve this problem. Here's what I came up with:
class Math
{
public static function round($number, $numberOfSigFigs = 1)
{
// If the number is 0 return 0
if ($number == 0) {
return 0;
}
// Deal with negative numbers
if ($number < 0) {
$number = -$number;
return -Math::sigFigRound($number, $numberOfSigFigs);
}
return Math::sigFigRound($number, $numberOfSigFigs);
}
private static function sigFigRound($number, $numberOfSigFigs)
{
// Log the number passed
$log = log10($number);
// Round $log down to determine the integer part of the log
$logIntegerPart = floor($log);
// Subtract the integer part from the log itself to determine the fractional part of the log
$logFractionalPart = $log - $logIntegerPart;
// Calculate the value of 10 raised to the power of $logFractionalPart
$value = pow(10, $logFractionalPart);
// Round $value to specified number of significant figures
$value = round($value, $numberOfSigFigs - 1);
// Return the correct value
return $value * pow(10, $logIntegerPart);
}
}
While the functions here worked, I needed significant digits for very small numbers (comparing low-value cryptocurrency to bitcoin).
The answer at Format number to N significant digits in PHP worked, somewhat, though very small numbers are displayed by PHP in scientific notation, which makes them hard for some people to read.
I tried using number_format, though that needs a specific number of digits after the decimal, which broke the 'significant' part of the number (if a set number is entered) and sometimes returned 0 (for numbers smaller than the set number).
The solution was to modify the function to identify really small numbers and then use number_format on them - taking the number of scientific notation digits as the number of digits for number_format:
function roundRate($rate, $digits)
{
$mod = pow(10, intval(round(log10($rate))));
$mod = $mod / pow(10, $digits);
$answer = ((int)($rate / $mod)) * $mod;
$small = strstr($answer,"-");
if($small)
{
$answer = number_format($answer,str_replace("-","",$small));
}
return $answer;
}
This function retains the significant digits as well as presents the numbers in easy-to-read format for everyone. (I know, it is not the best for scientific people nor even the most consistently length 'pretty' looking numbers, but it is overall the best solution for what we needed.)

Categories