Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: locale-dependent float to string cast

I'm sitting on a machine with en_US locale and this piece of PHP code

setlocale(LC_ALL,'de_DE.utf8');
var_dump((string)1.234);

returns

string(5) "1.234"

whereas on my colleague's machine which has a German locale, it returns

string(5) "1,234"

Why the heck does PHP use the locale when typecasting floats to strings? How can I disable it? I'd like to have this function return string(5) "1.234" on all machines, regardless of any locale settings.

Secondly and less important: Why does PHP ignore the setlocale on my machine?

like image 817
Treecj Avatar asked Jul 11 '13 07:07

Treecj


1 Answers

Why the heck does PHP use the locale when typecasting floats to strings?

That's its behaviour

How can I disable it?

You can't (as far as I know).

You may set locale to en_US if you have locale installed.

I'd like to have this function return string(5) "1.234" on all machines, regardless of any locale settings.

You have two options:

1) number_format(1.234, 3, '.', '');

2) sprintf('%.3F', 1.234);

In both cases you have to specify how may decimal digits you want.

In the second case you may not specify them and get a default value of 6.

If you don't want the trailing zeroes you may trim them.

Secondly and less important: Why does PHP ignore the setlocale on my machine?

As DevZer0 commented you may not have locale installed.

like image 71
Paolo Avatar answered Oct 30 '22 14:10

Paolo