Nov 25 2008

There’s a couple of ways to remove decimal places from a number in PHP…

$out = number_format($val,0);
$out = (int) @floor($val);

Interestingly, we ran a real-world test case of 10 million iterations of doing each of these, and it turns out that method #2 is approximately 0.5 seconds quicker. So there you have it, if you want to be 0.5 seconds quicker when removing decimal places from a number 10 million times.. then use the second method.

6 Responses to “Getting Rid of Decimal Places in PHP”

  1. David says:

    Why the call to floor()?

    for( $i = 1; $i ” . (int) $i . “\n”;
    }

  2. Jasper says:

    Damn you David! I was just going to say that – you then remove the need to call the error suppression operator, which might save you another 0.5 seconds.

  3. James says:

    I didn’t write the second way heh, I agree – it was our Technical team leader who did that haha… interpret that as you will :)

  4. Jasper says:

    Sounds like the words in his job title need to be reordered by relevance ;)

  5. Kelvin says:

    It was a “quick fix” for a live script ;)

  6. David says:

    Hmm… my example rendered as symbol-salad. Weird. Here’s a neat one we picked up somewhere (if it renders):

    ( string )( ( int )$x ) == $x

    Returns false if $x is not an integer.

Leave a Reply