Round to Max Thousand, Hundred etc in PHP

Round to max thousand, hundred etc in PHP

Final implementation, inspired from Shaunkak's answer and SO's comment. Thanks for these bra..s. live demo

<?php
$val = 10241.67;
if($val >= 1000) {
echo ceil($val / 1000) * 1000;
}
else {
$length = strlen(ceil($val));
$times = str_pad('1', $length, "0");
echo ceil($val / $times) * $times;
}

How to round to nearest Thousand?

PHP allows negative precision for round such as with:

$x = round ($x, -3); // Uses default mode of PHP_ROUND_HALF_UP.

Whereas a positive precision indicates where to round after the decimal point, negative precisions provide the same power before the decimal point. So:

n    round(1111.1111,n)
== ==================
3 1111.111
2 1111.11
1 1111.1
0 1111
-1 1110
-2 1100
-3 1000

As a general solution, even for languages that don't have it built in, you simply do something like:

  • add 500.
  • divide it by 1000 (and truncate to integer if necessary).
  • multiply by 1000.

This is, of course, assuming you want the PHP_ROUND_HALF_UP behaviour. There are some who think that bankers rounding, PHP_ROUND_HALF_EVEN, is better for reducing cumulative errors but that's a topic for a different question.

PHP round value to it's own size (ten, hunderd, thousand)

May be You mean this

function Myround(array $numbers)
{
$new_numbers = [];
foreach ($numbers as $num) {
$rozriad = strlen($num)-1;
$new_numbers[] = round(ceil($num/pow(10, $rozriad))*pow(10, $rozriad), -$rozriad);
};
return $new_numbers;
};

$dozens = [5, 51, 100, 121, 999, 1001];

print_r(Myround($dozens));

Round to Highest Factor with Variable Scale?

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

How to round up a number to nearest 10?

floor() will go down.

ceil() will go up.

round() will go to nearest by default.

Divide by 10, do the ceil, then multiply by 10 to reduce the significant digits.

$number = ceil($input / 10) * 10;

Edit: I've been doing it this way for so long.. but TallGreenTree's answer is cleaner.

Increment Price by Hundred, Thousand, Ten-Thousand, etc

  1. Get power of 10: log10(1234); // 3.09131
  2. Round down: floor(log10(1234)); // 3
  3. Re-raise as power of 10: pow(10,floor(log10(1234))); // 1000
  4. ???
  5. Profit.

Show a number to two decimal places

You can use number_format():

return number_format((float)$number, 2, '.', '');

Example:

$foo = "105";
echo number_format((float)$foo, 2, '.', ''); // Outputs -> 105.00

This function returns a string.

PHP Rouding 44947 to 44900

Use floor

echo floor(1940/100)*100;

Round will round it - so .6 becomes 1, floor rounds off, so .6 becomes 0.

So...

echo floor(1960/100)*100;
echo round(1960,-2);

will give 1900 and 2000

Unfortunately you can't use the same thing as round and specify a number of DP's, so the /100*100 does that job.



Related Topics



Leave a reply



Submit