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
);

Demonstration:

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

1 comment / Add your comment below

  1. Hey thanks man, I almost gave up! I was working on an accounting application and needed to format some numbers and vice versa. I was just getting single digit numbers by float conversions 😂

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.