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:
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:
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:
And that’s not the only way to get a ‘wrong’ floating point number. Take the following code for example:
1 2 3 4 5 6 7 8 |
setlocale(LC_ALL, 'nl_NL'); echo (float)"10.5000" . "\n"; // 10,5 echo floatval("10.5000") . "\n"; // 10,5 echo number_format("10.5000", 2) . "\n"; // 10.50 echo number_format("10,5000", 2) . "\n"; // 10.00 echo sprintf("%f", "10.5000") . "\n"; // 10,500000 echo sprintf("%f", 10.5000) . "\n"; // 10,500000 echo 10.5000 . "\n"; // 10,5 |
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.5 out of 5.
How would you rate this article?
★ ★ ★ ★ ★