3

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)
guillaume
  • 1,638
  • 5
  • 24
  • 43

5 Answers5

5

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.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
0

Tested this:

$dataValue = "4,02";
$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>";

Output:

string(4) "4,02"
string(4) "4.02"
float(4.02)
float(4.02) 

Are you sure that the posted code produces the described problem?

EDIT

Try add this this:

$dataValue = preg_replace("/[^0-9\,]/", '', $dataValue);
Bogdan Burym
  • 5,482
  • 2
  • 27
  • 46
0

Use number_format(float_number, decimal_places):

var_dump(number_format(floatval($dataValue) ,2));
mallix
  • 1,399
  • 1
  • 21
  • 44
0

I believe the difference lies in the fast that $dataValue is a double-quoted string in the third output, while you use a single-quoted string in the fourth example. In PHP, these work differently when dealing with how they are treated as literals.

Community
  • 1
  • 1
Southpaw Hare
  • 1,535
  • 3
  • 24
  • 50
0

I am going to assume it has to do with accuracy issues in PHP's float implementation.

Check out this: Wikipedia: Floating Point Accuracy Problems

Erik
  • 12,730
  • 5
  • 36
  • 42