# Thread: rounding up a decimal

1. How do I round up a decimal and turn it to an integer in php. Say for example if i have

0.4 i want it to go to 1
4.3 to go to 5
3.01 to go to 4

etc.

I guess it is using (number_format (\$variable, ?))

but i can't seem to work it out and get weird results. Any ideas?

2. Use ceil()

Syntax: int ceil (float number)

3. perfect! thanks so much

4. Just for the sake of it...

A generic (non php specific) algorithms for rounding numbers:

Code:
```1) ROUND DOWN

\$myInt = (int)\$myDouble;

2) ROUND OFF

\$myInt = (int)(\$myDouble + 0.5);

3) ROUND UP

if (\$myDouble == (int)\$myDouble) {
\$myInt = \$myDouble;
} else {
\$myInt = (int)(\$myDouble + 1);
}```
Hmm, I must be bored to be posting useless code

5. Just for the sake of uselessness:

ROUND UP SHOULD BE

PHP Code:
```    \$myInt = (\$myDouble == (int)\$myDouble) ? \$myDouble : (int)(\$myDouble + 1);  ```

6. If we are going to be useless I will join in.

Round up could be done this way:

\$myInt = \$myInt + 1;
\$myInt = (int)\$myDouble;

7. Thankyou Freddie - elegent use of the ternary operator, however the logic is just the same

However, given this is a generic algorithm - I forgot to cast to int in one spot which would be important if we were using a strongly typed language and not PHP.
Code:
`\$myInt*=*(\$myDouble*==*(int)\$myDouble)*?*(int)\$myDouble*:*(int)(\$myDouble*+*1);`
Mart H - that code doesn't work as intentded.

Deskcheck:

\$myInt = 0, \$myDouble = 10.123
Expected Result: \$myInt = 11

line 1)
\$myInt = 0 + 1 = 1

line 2)
\$myInt = (int)10.123 = 10

Result == Expected ?
10 != 11
Deskcheck failed

8. oh my.. what have i done

9. freakysid,

I told you that I was joining in just to be useless.

Actually there was a small typo there.

\$myDouble = \$myDouble + 1;
\$myInt = (int)\$myDouble;

No lets do the deskcheck

\$myInt = 0, \$myDouble = 10.123
Expected Result: \$myInt = 11

line 1)
\$myDouble = 10.123+ 1 = 11.123

line 2)
\$myInt = (int)11.123 = 11
Result == Expected ?
11 = 11
Deskcheck Succeeds.

10. OK - so what about if \$myDouble = 10.00
Does the algorithm work then?

11. Like I said, I am just trying to be useless!! And doing very good at it if I may say so myself. And to think I have a math degree.

/Marty slinks away with tail between legs

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•