Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP round decimals

Tags:

php

rounding

Is it possible to round a decimals to the nearest .5 with PHP like this:

number | round
----------------
 1.29  |  1.50
 2.03  |  2.00
 1.43  |  1.50
 1.13  |  1.00
11.38  | 11.50

I tried with:

$rnd= round($number,2);

but I get decimals like the one in the column "number" above.

like image 375
Sergio Avatar asked Jun 22 '10 14:06

Sergio


People also ask

How do I round to 2 decimal places in PHP?

Example #1 round() examples php echo round(3.4); // 3 echo round(3.5); // 4 echo round(3.6); // 4 echo round(3.6, 0); // 4 echo round(1.95583, 2); // 1.96 echo round(1241757, -3); // 1242000 echo round(5.045, 2); // 5.05 echo round(5.055, 2); // 5.06 ?>

How do you round up decimals in PHP?

The round() function rounds a floating-point number. Tip: To round a number UP to the nearest integer, look at the ceil() function. Tip: To round a number DOWN to the nearest integer, look at the floor() function.

How do you round decimals?

There are certain rules to follow when rounding a decimal number. Put simply, if the last digit is less than 5, round the previous digit down. However, if it's 5 or more than you should round the previous digit up. So, if the number you are about to round is followed by 5, 6, 7, 8, 9 round the number up.

How do you round a number to the nearest 5 in PHP?

So, ceil( $the_number / 5 ) * 5 is the final answer. Or round( $the_number / 5 ) * 5 if you want to round to the nearest 5.


1 Answers

function round_to_nearest_half($number) {
    return round($number * 2) / 2;
}
like image 66
Artefacto Avatar answered Oct 15 '22 15:10

Artefacto