开发者

PHP - floatval cuts of position after decimal point?

I have this PHP code:

<?p开发者_JS百科hp
    $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...


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


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜