Re: Inconsistent float to string vs. string to float casting

From: Date: Thu, 27 Dec 2018 16:33:35 +0000
Subject: Re: Inconsistent float to string vs. string to float casting
References: 1  Groups: php.internals 
Request: Send a blank email to internals+get-103642@lists.php.net to get a copy of this message
cmbecker69@gmx.de ("Christoph M. Becker") wrote: > Hi! > > Regarding the decimal separator (aka. decimal point), the behavior of > casting float to string is inconsistent with casting string to float. > [...] I'm shocked... Lot of code here assumes (float) does the exact reverse of (string); forunately most servers are configures with the default locale "C", but I'm still concerned for libraries portability. Did you filed a bug for that? Anyway, here is some test code I wrote: <?php // test-float-cast.php /** * Performs string to float and float to string tests vs. locale. * @param string $loc LC_NUMERIC locale to set for the test. */ function test($loc) { if( setlocale(LC_NUMERIC, $loc) === FALSE ) throw new RuntimeException("setlocale() failed"); // Cast float to string test: $exp = "0.5"; $got = (string) 0.5; if( $got !== $exp ) echo "FAILED with LC_NUMERIC=$loc, (string) 0.5: got $got, exp $exp\n"; // Cast string to float test: $exp = 0.5; $got = (float) "0.5"; if( $got !== $exp ) echo "FAILED with LC_NUMERIC=$loc, (float) \"0.5\": got $got, exp $exp\n"; // printf() formatting of float: $exp = "0.500000"; $got = sprintf("%f", 0.5); if( $got !== $exp ) echo "FAILED with LC_NUMERIC=$loc, sprintf(\"%f\", 0.5): got $got, exp $exp\n"; } test("C"); test("de"); Output: FAILED with LC_NUMERIC=de, (string) 0.5: got 0,5, exp 0.5 FAILED with LC_NUMERIC=de, sprintf("%f", 0.5): got 0,500000, exp 0.500000 The second failed test is expected, as printf, scanf and co. are intended to be locale-aware. But the first one? Is there any simple, efficient and safe way to convert back a string into float? Regards, ___ /_|_\ Umberto Salsi \/_\/ www.icosaedro.it

« previous php.internals (#103642) next »