Hein
Hein

Reputation: 921

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...

Upvotes: 5

Views: 10157

Answers (3)

Bob
Bob

Reputation: 831

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
?>

Upvotes: 3

Xyz
Xyz

Reputation: 6013

1,99 is not a valid php float. The issue is your comma (,). In PHP you have to use dot (.) as floating point separator.

<?php
    $float = "1.99";
    echo "<p>$float<br>";
    $float = (float)$float; 
    $val = number_format($float, 2,'.', ',');
    echo "$float</p>";
?>

Upvotes: 1

Stefan Gehrig
Stefan Gehrig

Reputation: 83632

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>";

Upvotes: 7

Related Questions