Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - floatval cuts of position after decimal point?

I have this PHP code:

<?php
    $float = "1,99";
    echo "<p>$float<br>";
    $float = floatval($float); // Without this line number_format throws a notice "A non well formed numeric value encountered" / (float) $float leads to the same output
    $val = number_format($float, 2,'.', ',');
    echo "$float</p>";
?>

Why does it return 1? Don't get that.

And: yes, there is a sense in converting 1,99 to 1,99 ;-)

Thanks for advise...

like image 256
Hein Avatar asked Dec 27 '22 13:12

Hein


2 Answers

The problem is, that PHP does not recognize the , in 1,99 as a decimal separator. The float type is defined as having the following formal definition:

LNUM          [0-9]+
DNUM          ([0-9]*[\.]{LNUM}) | ({LNUM}[\.][0-9]*)
EXPONENT_DNUM [+-]?(({LNUM} | {DNUM}) [eE][+-]? {LNUM})

That means it'll only accept . as a decimal separator. That's in fact the same reason why number_format throws a warning on an invalid datatype because it cannot convert 1,99 to a float internally.

The following should work:

$float = "1,99";
echo "<p>$float<br>";
$val = number_format(str_replace(',', '.', $float), 2,'.', ',');
echo "$float</p>";
like image 172
Stefan Gehrig Avatar answered Jan 10 '23 22:01

Stefan Gehrig


floatval recognizes the comma (,) as a character and not as a number, so it cuts off everything that comes after it. In this case, that's the 99. Please use a dot (.) instead of a comma (,) and it will probably work.

Example floatval (source: http://php.net/manual/en/function.floatval.php):

<?php
$var = '122.34343The';
$float_value_of_var = floatval($var);
echo $float_value_of_var; // 122.34343
?>
like image 34
Bob Avatar answered Jan 10 '23 21:01

Bob