21

I'trying to convert a float to an int value in php:

var_dump((int)(39.3 * 100.0)); //Returns 3929 but should be 3930!
var_dump((int)(39.2 * 100.0)); //Returns 3920

I can use ceil to make it work but can somebody explain this to me?

var_dump((int)ceil(39.3 * 100.0)); //Returns 3930
mskfisher
  • 3,291
  • 4
  • 35
  • 48
dan
  • 507
  • 2
  • 9
  • 14

4 Answers4

25

This is because numbers that have a finite representation in base 10 may or may not have an exact representation in the floating point representation PHP uses.

See

>php -r "echo var_dump(sprintf('%.40F', 39.3 * 100.0));"
string(45) "3929.9999999999995452526491135358810424804688"

Since int always rounds the number down, a small error in the representation makes the cast round it one number down that you would otherwise expect.

Consider using round instead.

Artefacto
  • 96,375
  • 17
  • 202
  • 225
17

This might be late but the proper way to do it is as follows:

(int) bcmul("39.3", "100.0"); // 3930
(int) bcmul("39.2", "100.0"); // 3920

and for dealing with digits / calculation for floats, or anything that involves money transaction, you should never use directly multiplication/division + casting.

please refer to this as well:

http://php.net/manual/en/book.bc.php

notice: the casting in my answer is just to convert String to Int, (you don't need to do it)

Shehabic
  • 6,787
  • 9
  • 52
  • 93
4
// gives: int(3930)
var_dump(intval((39.3 * 100.0) . '')); 

or, for use with a function:

function floatToInteger ($fValue)
{
    return (intval(($fValue + 0) . ''));
}

// gives: int(3930)
var_dump(floatToInteger(39.3 * 100.0));
1

You should have a look at this page: http://php.net/manual/en/language.types.float.php. It describes the pitfalls working with floating point numbers.

Dennis Haarbrink
  • 3,738
  • 1
  • 27
  • 54
  • Another good reference that shows this is a common issue for most computer languages is http://en.wikipedia.org/wiki/Floating_point#Accuracy_problems – Mark Baker Aug 02 '10 at 07:42