|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2009-05-18 15:26 UTC] alef0 at freenet dot de
Description:
------------
PHP version: 5.2.6RC4-pl0-gentoo
Conversion using floatval() or (float) respects the numeric settings of the locale.
THIS IS VERY DANGEROUS CAUSE YOU WILL GET WRONG RESULTS BY APPLYING ANY MATH METHODE ON CONVERTED FLOATS!
Reproduce code:
---------------
$var = '122.34343The'; //expected float: 122.34343
setlocale(LC_NUMERIC, 'en_US.utf8');
$float_value_of_var = (float) $var;
print 'Locale dec sep point: (float) ' . $var . ' = ' . $float_value_of_var;
$float_value_of_var = floatval($var);
print ' or floatval(' . $var . ') = ' . $float_value_of_var . "<br /><br />\n\n";
setlocale(LC_NUMERIC, 'de_DE.utf8');
$float_value_of_var = (float) $var;
print 'Locale dec sep comma: (float) ' . $var . ' = ' . $float_value_of_var;
$float_value_of_var = floatval($var);
print ' or floatval(' . $var . ') = ' . $float_value_of_var . "<br /><br />\n\n";
Expected result:
----------------
Locale dec sep point: (float) 122.34343The = 122.34343 or floatval(122.34343The) = 122.34343
Locale dec sep comma: (float) 122.34343The = 122.34343 or floatval(122.34343The) = 122.34343
Actual result:
--------------
Locale dec sep point: (float) 122.34343The = 122.34343 or floatval(122.34343The) = 122.34343
Locale dec sep comma: (float) 122.34343The = 122,34343 or floatval(122.34343The) = 122,34343
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Wed Oct 29 02:00:01 2025 UTC |
> $var = '122.34343The'; //expected float: 122.34343 > $float_value_of_var = floatval($var); > > Conversion using floatval() or (float) respects the > numeric settings of the locale. No, just make a: | var_dump($float_value_of_var); > print ' or floatval(' . $var . ') = ' . $float_value_of_var ."\n\n"; You are casting a float to a string, and that's where locale comes in place. See [1]. And is this not the reason for setlocale: to output dates/currencies/numbers/... according to a language setting? If you want output the float value locale aware in a string, you can use printf() with the "%F" modifier. Regards, Carsten [1] http://de.php.net/manual/en/language.types.string.php#language.types.string.casting