I need to store numbers that represent currency amounts in 2dp to be output to the screen. The same number may be altered with mathematical functions after being formatted. I’m sure I remember having errors in the past as a result of the number formatted number being treated as a string, and the thousand separator being the cause of the problem, but the below script runs without errors.
Is PHP’s loose data types saving the day here? Did something change in a relatively recent PHP version? If not, are there other circumstances where number_format() can still cause a mathematical function to fail because the number is a string?
echo round(1111123.2, 2); //included to demonstrate how it can't be used for this purpose
echo "<br />";
echo number_format(1111123.2, 2);
echo "<br />";
$num = number_format(1111123.2, 2);
echo number_format($num / 42, 2);
// output
1111123.2
1,111,123.20
0.02
Never do this. It’s bound to end in tears, for example when you format numbers with non-english decimal separators. Do the operations on the raw numeric value, then format immediately before outputting.