Rounding

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Bon Bon
Forum Commoner
Posts: 66
Joined: Sat Mar 13, 2004 10:21 pm
Location: UK

Rounding

Post by Bon Bon »

I do not know if I am being thick here but I am pretty sure there is an easy way of rounding the last 3 digits of a number based on the value of the last 4 numbers.

For example:
100023 rounds to 100500
100499 rounds to 100500
100500 rounds to 101000
100501 rounds to 101000
100523 rounds to 101000

I did think about using a substr on the last 3 numbers or something and then using round but I was hoping for something a bit more advanced but easier to read. If anybody could help there I would appreciate it.
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Re: Rounding

Post by Chris Corbyn »

Code: Select all

$number = 100563;
 
echo round($number / 1000) * 1000;
EDIT | In your case actually you want to replace 1000 with 100.
EDIT 2 | :lol: sorry I was right the first time...
Bon Bon
Forum Commoner
Posts: 66
Joined: Sat Mar 13, 2004 10:21 pm
Location: UK

Re: Rounding

Post by Bon Bon »

I was never good with math, spot on.

*Edit*
I used the following code, if anyone can do better please post a better solution, but if not please use the following for a reference:

Code: Select all

$price = substr($price, -3) > 500 ? round($price/1000)*1000 : round($price/1000)*1000 + 500;
Post Reply