photo credit: Golden Boy via photopin (license)

Floating point numbers in PHP and your system locale

Tags: , ,

So the other day I had a strange issue with a certain part on a Magento webshop that I was working on: The checkout wasn’t working. It turned out that there was a parsing error in the JavaScript that stopped the execution of the rest of the script:

Screen Shot 2015-09-23 at 14.57.58
Needless to say, in the snippet above it’s clear what’s going wrong: a floating point number in JavaScript needs to be formatted with a dot, not a comma. So I looked up the code of the PHP script that was responsible for this line:

Screen Shot 2015-09-23 at 14.58.09
Wait, that’s strange! PHP just casts a variable to a floating point number. Shouldn’t that do the trick?

The short answer: No

A simple setup I did proved that casting a variable to a floating point number uses the system locale to format the number. For example: in Dutch the decimal separator is a comma, not a dot. So if you take a look at the following example you’ll see what happens:

Screen Shot 2015-09-23 at 14.58.31
And that’s not the only way to get a ‘wrong’ floating point number. Take the following code for example:

As you can see in this example, the only accurate method to cast a variable to a floating point number in your PHP code to use in JavaScript (or any other format like SQL queries for example), is to use the number_format() -function to make sure your floating point number is bullet-proof.

Visitors give this article an average rating of 2.6 out of 5.

How would you rate this article?

Leave a Reply