Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Round to nearest and least multiple of 10

Tags:

php

laravel

So here is my situation. I have a couple of numbers where I want to round to the nearest and least multiple of 10.

For example values in between 51 to 59 should round to 50.

Input = 59 = >Respose = 50

Input = 51 => Respose = 50

I have tried

$number = round(53, -1);

which will gives be 50 which is correct which I want, but if I try with 56, it will give me 60. But here also, am expecting 50. Can somebody help me out?

Accepted answer (In case some one is reading the question)

floor($number / 10)*10

However ,it gives be decimal values which I round and changed to

$amount = (int)floor($amount / 10)*10;
like image 726
Arun Code Avatar asked Dec 07 '22 19:12

Arun Code


1 Answers

Use floor instead; first dividing by 10 then multiplying the truncated result back up:

$number = floor($number / 10) * 10

Using solutions such as $number = round($number - 5, -1); can cause you problems with floating point edge cases. (Interestingly that's how early Java implementations did it, with disastrous results.)

like image 91
Bathsheba Avatar answered Dec 10 '22 23:12

Bathsheba