Weird result when converting string to float

floating-point, php

Solution

There are only 4 visible characters, yet `var_dump()` claims that there are 7. I surmise that there is an invisible character before the decimal point that is causing `floatval()` to terminate conversion prematurely. You can verify this by looking at a hex dump of the contents of `$dataValue`.

EDIT:

It appears that your string is encoded in UTF-16LE. Use mb or iconv to convert it to ASCII/UTF-8 before processing.

Problem

I want to convert a string to float but I've some problem. Here is my code ``` $dataValue = $item[$data]; $dataValue = trim($dataValue); var_dump($dataValue);echo "<br>"; $dataValue = str_replace(',', '.', $dataValue); var_dump($dataValue);echo "<br>"; var_dump(floatval($dataValue));echo "<br>"; var_dump(floatval('4.02'));echo "<br>"; ``` And the results ``` string(7) "4,02" string(7) "4.02" float(4) float(4.02) ``` I don't understand the third result, why I have 4 and not 4.02 ? Thanks EDIT: My new code : ``` $dataValue = $item[$data]; echo mb_detect_encoding($dataValue) . "<br>"; $dataValue = iconv('ASCII', 'UTF-8//TRANSLIT', $dataValue); $dataValue = trim($dataValue); $dataValue = str_replace(',', '.', $dataValue); echo mb_detect_encoding($dataValue) . "<br>"; var_dump($dataValue);echo"<br >"; $dataValue = mb_convert_encoding($dataValue, "UTF-8"); var_dump($dataValue);echo"<br >"; $dataValue = str_replace(',', '.', $dataValue); $dataValue = floatval($dataValue); var_dump($dataValue);echo"<br >";` ``` And the result ``` ASCII ASCII string(7) "4.02" string(7) "4.02" float(4) ```

Original source

Related problems