TalkPHP (http://www.talkphp.com/forums.php)
-   Absolute Beginners (http://www.talkphp.com/absolute-beginners/)
-   -   Floating point to integer? (http://www.talkphp.com/absolute-beginners/2128-floating-point-integer.html)

 Haris 01-28-2008 06:13 PM

Floating point to integer?

For example, if the value of a integer called number is 4856756.55, it should be converted to 4856757. I thought there was a default function by PHP for that but I couldn't find any function. Type juggling doesn't work!!! ARGH!!! *!*

 Alan @ CIT 01-28-2008 06:21 PM

When converting from a float to an int, PHP just strips the decimal point and everything after it. For example:

PHP Code:

``` <?php echo (int) 4856756.55; // echo's 4856756 ```
Take a look at my article on Variables for more info: TalkPHP - Variables for Beginners :-)

For more precise numbers, you'll need to use the BCMath extension in PHP: PHP: BC math - Manual

Alan

 RobertK 01-28-2008 06:28 PM

Err... round() works too. You can even specify the precision.

PHP Code:

``` \$float = 4856756.55; echo round(\$float);  ```

 ReSpawN 01-28-2008 06:35 PM

My thought exactly. You can also simply explode on the dot and then print the \$float[1]... ;-)

 Alan @ CIT 01-28-2008 06:37 PM

I think my memory is going, using round() didn't even occur to me, was just thinking of typecasting. Must be getting old :-(

Alan.

 ReSpawN 01-28-2008 06:43 PM

Quote:
 Originally Posted by Alan @ CIT (Post 9863) I think my memory is going, using round() didn't even occur to me, was just thinking of typecasting. Must be getting old :-( Alan.
Let me scare you in that case... ever heard of ceil()? :-P

 Wildhoney 01-28-2008 07:41 PM

...And floor() !

 Alan @ CIT 01-28-2008 07:50 PM

Doesn't intval() just do the same as typecasting to int and always round down?

Alan

 ReSpawN 01-28-2008 07:55 PM

Correct. ;-)
PHP Code:

``` \$rNumber1 = 10;\$rNumber2 = 13.37;intval(\$rNumber1); // Returns 10intval(\$rNumber2); // Returns 13  ```
It also works with large -e numbers and negative values.
Code:

`(like 26.98 - 13 = -13.98 => -13)`

 xenon 01-28-2008 08:32 PM

intval doesn't round anything. it just returns the integer part of the number. number_format rounds the number automatically (depending on the decimal precision).

PHP Code:

``` echo intval(13.397); // 13echo intval(15.99); // 15echo number_format(15.56, 0, '', ''); // 16echo number_format(12.21, 0, '', ''); // 12  ```

 RobertK 01-28-2008 08:37 PM

Actually, that isn't rounding down is -13.98 yields 13, that's just dropping the decimal value. -13.98 rounds down to -14, not -13. Technically that should be a call to floor(), but the results are disparate.

 All times are GMT. The time now is 09:55 PM.