Quick Tips · February 18, 2019 1

PHP: Fixing the floatval() problem with number_format()

This is probably not a matter many will come across in their work. But I almost tore my beards off recently.

The problem: there were a bunch of currency amounts being parsed by number_format() and I needed to parse them back to 2 decimal floats. However, this happened:

As you can see, (float) or floatval($var) is returning just the first number of the whole value.

number_format() returns a string. That string has a thousands seperator and a decimal seperator.

floatval() or (float) thinks that the first comma in 4,116 is the decimal separator and just returns the very first number instead (or that’s how I understood it).

The Fix

In your number_format() do this instead:

$num1 = (float) number_format(
    (float) 8231 /2, // the number to format
    2, // how many decimal points
    ".", // decimal separator
    "" // thousands separator, set it to blank


it will also work with type assignment (float) or (double)