Round small numbers - php

I would like to know how to achieve this:
round(0.38)
And receive this:
0.40
How can I do this? I tried with round(0.38, 2) but it does not work.

To get 0.4, round to 1 decimal place using round() where the second parameter is the decimal place.
$rounded_number = round(0.38, 1);
To get 0.40, use number_format() to get 2 decimal places.
$formatted_number = number_format( $rounded_number , 2);

Multiply by ten, round, then divide by ten:
php > $a = 0.38;
php > $b = $a * 10;
php > $c = round($b);
php > echo $c/10;
0.4

If you want the two decimal places:
$num = 0.38;
$num = round($num * 10)/10;
$num = number_format($num, 2);
echo $num;

It is probably far simpler than you think it is:
$num = round(0.38 * 10)/10;
echo $num;
Then, you could just replace 0.38 with another number or a variable.

$a = 0.38;
echo sprintf("%.2F", round($a,PHP_ROUND_HALF_UP));

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 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;

Add a decimal after two first numbers

I am generating some data of latitude and longitude with rand(10000000, 3000000); for example. But I need to calculate distance between two locations, so basically I need to convert my result, for example 22049256 to 22.049256 in order to pass to my function.
How can I achieve this most effectively with using least amount of resources?
TL;DR
I have integer 22049256, needs to be converted to float 22.049256.
Divide by 1M?
22049256 / 1000000 = 22.049256
$foo = rand(10000000, 30000000);
$foo /= 1000000;
echo $foo;
If you always want the decimal after the first two digits, that should do the trick.
<?php
$n = rand(10000000, 3000000);
$len = strlen($n);
$div = pow(10, $len - 2);
$n /= $div;
var_dump($n);
?>
http://codepad.viper-7.com/Nrql15
Basically just dividing by a number made by checking how many characters there are in your original number.
Simplest way would be to treat the number as a string and iterate through it, adding the decimal point at the appropriate position.
$new_number = '';
for($i=0;$i<strlen((string)$number;$i++)
{
if($i == 2)
$new_number .= '.';
$new_number .= substr((string)$number, $i, 1);
}
Edit:
Another possibility is to divide by 1000000 and run number_format to ensure proper decimal places:
$new_number = number_format($number/1000000, 6);

how to round up to the next x20 number with php?

I know ceil, which will round 15.1 to 16 and 31.2 to 32.
But how to round up to the next x20 number? like 15.1 to 20 and 31,2 to 40?
Is needed to make sensefull labels for the y-axis of a chart.
Try this (works in JavaScript):
$result = 20 * ceil($input / 20);
Here, we're rounding to 20. To round to other numbers, simply replace 20 with whatever base you want. The documentation for ceil() can be found here.
A function that does the same:
function roundTo($value, $base)
{
return $base * ceil($value / $base);
}
As a small aside, if you want to round to the nearest base, instead of rounding up, use round() instead of ceil().
divide by 20 and use ceil, then multiply by 20
Or you could use modulus:
echo round($a + 20 - ($a % 20));
If you want "mid-range" values to round more, you can use the following.
function roundTo($n,$i = 1){
$r = $n % $i;
$d = round(($n - $r * $i) / $i);
return $r * $i + $d * $i;
}
for ($a = 0; $a < 100; $a++){
printf("%d = %d\r\n", $a, ceil2($a, 20));
}
The above produces:
Number: Rounded To:
0-10 0
11-30 20
31-50 40
etc.
This more closely simulates how 1.3=1 but 1.5=2.
you can use this
ceil(x/2)*2

Split a number by decimal point in php

How do I split a number by the decimal point in php?
I've got $num = 15/4; which turns $num into 3.75. I would like to split out the 3 and the 75 parts, so $int = 3 and $dec = 75. My non-working code is:
$num = 15/4; // or $num = 3.75;
list($int, $dec) = split('.', $num);
but that results in empty $int and $dec.
Thanks in advance.
If you explode the decimal representation of the number, you lose precision. If you don't mind, so be it (that's ok for textual representation). Take the locale into account! We Belgians use a comma (at least the non-programming ones :).
If you do mind (for computations e.g.), you can use the floor function:
$num = 15/4
$intpart = floor( $num ) // results in 3
$fraction = $num - $intpart // results in 0.75
Note: this is for positive numbers. For negative numbers you can invert the sign, use the positive approach, and reinvert the sign of the int part.
$num = 15/4; // or $num = 3.75;
list($int, $dec) = explode('.', $num);
Try explode
list($int,$dec)=explode('.', $num);
as you don't really need to use a regex based split. Split wasn't working for you as a '.' character would need escaping to provide a literal match.
$int = $num > 0 ? floor($num) : ceil($num);
$dec = $num - $int;
If you want $dec to be positive when $num is negative (like the other answers) you could do:
$dec = abs($num - $int);
$num = 3.75;
$fraction = $num - (int) $num;
In case when you don't want to lose precision, you can use these:
$number = 10.10;
$number = number_format($number, 2, ".", ",");
sscanf($number, '%d.%d', $whole, $fraction);
// you will get $whole = 10, $fraction = 10
This works for positive AND negative numbers:
$num = 5.7;
$whole = (int) $num; // 5
$frac = $num - (int) $num; // .7
$num = 15/4;
substr(strrchr($num, "."), 1)

Categories