I have a problem with converting string to float.
print gettype($value[$id]); //returns string
var_dump($value[$id]);//returns string '34,7140' (length=7)
$float = floatval($value[$id]);
print gettype($float);//returns double
var_dump($float);//returns float 34
echo $float;//returns 34
I don't understand why "34" ? Why $float is not '34,7140'?
How can I get $float = 34,7140 ?
The problem is that floats are expected to be in the English format with a
.
separating the decimal part, not a comma. If the format is always the same with a single comma, use this:The decimal separator in PHP (and most other computer languages) is the dot, not the comma:
Update: floatval() stops parsing the string as soon as it finds a non-numeric character. This is the example from the manual:
If you need to extract a number that's not in English format, you have to write your own code. Here's a suggestion:
Because "34,7140" is a string, as it contains a comma character.
You could use
$float = floatval(str_replace(',', '', $value[$id]));
to remove the comma character, or$float = floatval(str_replace(',', '.', $value[$id]));
to replace the comma with a decimal point, hence forcing PHP to interpret the number as 34.7140.