Jordi Canals wrote:
> I'm trying to understand how the intval() function works, but I'm
> unable to understand how exactly it works.

Deep deep inside the guts of the computer, $a is represented as something
not unlike:

800000e0

In other words, 8.00000 x 10 to the 0th power.

Now, when the computer has to convert that to an integer, the mathematics
involved are, well, pretty complex.

Basically, you're looking at a good solid semester of college-level
courses in computer science to *really* dig into all the guts of binary,
ones-complement, twos-complement, and other internal representations.

Also note that the way things are *really* stored is platform/OS
dependent, so you could get different results from intval() on, say,
Windows and Linux and Mac (and whatever else PHP runs on).

You can be quite sure it will always be 7 or 8 for this example, as the
number internally will be very very very close to 7.99999999999999... or
8.00000000000...

But (mostly) computers just don't think of decimal numbers and fractions
the same way you and I do, without some pretty special-purpose coding for
it.

Some real-world suggestions:

Use round(), floor() and ceil() as much as you can to convert if you are
worried about this kind of stuff.

If you *NEED* more precision for scientific purposes, the BC_MATH
extension lets *you* decide how many decimal points to keep around, and
you can get as precise as you want -- Up to the limits of the RAM on your
machine, and at a severe performance penalty compared to the built-in
OS-dependent math.

It should also be noted that there are languages (EG Lisp) which actually
*DO* understand fractions as part of the language specification, and which
just maybe might be more suitable for whatever it is you are doing if
PHP's "math" is frustrating you.  I suspect somebody somewhere has some
kind of fractional math package you could integate with PHP, though, if
you dig for it.

Keep in mind that it's not even really the way PHP thinks of numbers when
you are trying to figure out what intval() is doing -- It's built into the
hardware and the Operating System, and PHP pretty much just spits out
whatever the OS tells it to for intval().

-- 
Like Music?
http://l-i-e.com/artists.htm

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to