Stack Overflow Asked by Piemol on February 28, 2021
In PHP I found out that when a decimal is printed to screen (or: when it’s cast to string), the decimal separator will also be converted to a comma.
But why is that?
I haven’t found any documentation about this, and I don’t think casting to string takes internationalization settings into account.
Example code:
$var = 12.345;
var_dump($var); // Outputs: double(12.345)
var_dump((string)$var); // Outputs: string(6) "12,345"
var_dump(str_replace(',', '.', $var)); // Outputs: string(6) "12.345"
echo $var; // Outputs: 12,345
What causes this behavior?
This question applies to PHP < 8. According to the documentation,
As of PHP 8.0.0, the decimal point character is always
.
. Prior to PHP 8.0.0, the decimal point character is defined in the script’s locale (category LC_NUMERIC). See the setlocale() function.
If you read the manual, or check with google, you will find THIS.
The decimal point character is defined in the script's locale (category LC_NUMERIC)
Now, if you want to know which is the decimal point set on your sys :
print_r(localeconv());
Which returns :
Array
(
[decimal_point] => .
[...many other confs...]
)
If you want to set it use the good language : setlocale(LC_NUMERIC, $language)
I used fr_FR
to get a comma and en_US
to get a dot.
You should refer to the setlocale()
manual.
By the way, I don't know how to directly set the decimal_point
key of the array returned by localeconv()
without changing the entire LC_NUMERIC confs, if anyone knows, please edit :)
Answered by Bobot on February 28, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP