开发者

How to convert a string to float with "tail"?

I have a problem with converting string to float.

print gettype($value[$id]); //returns string

var_dump($value[$id]);//returns string '34,7140' (length=7)

$float = floatval($value[$id]); 

print gettype($float);//returns double

var_dump开发者_如何学编程($float);//returns float 34

echo $float;//returns 34

I don't understand why "34" ? Why $float is not '34,7140'?

How can I get $float = 34,7140 ?


The problem is that floats are expected to be in the English format with a . separating the decimal part, not a comma. If the format is always the same with a single comma, use this:

$float = (float)str_replace(',', '.', $value);


The decimal separator in PHP (and most other computer languages) is the dot, not the comma:

  • http://es2.php.net/manual/en/language.types.float.php

Update: floatval() stops parsing the string as soon as it finds a non-numeric character. This is the example from the manual:

<?php
$var = '122.34343The';
$float_value_of_var = floatval($var);
echo $float_value_of_var; // 122.34343
?>

If you need to extract a number that's not in English format, you have to write your own code. Here's a suggestion:

function to_decimal($string, $decimal_separator=',', $thousand_separator='.'){
    $value = strtr($string, array(
        $decimal_separator => '.',
        $thousand_separator => '',
    ));
    if( !is_numeric($value) ){
        return NAN;
    }
    return floatval($value);
}


Because "34,7140" is a string, as it contains a comma character.

You could use $float = floatval(str_replace(',', '', $value[$id])); to remove the comma character, or $float = floatval(str_replace(',', '.', $value[$id])); to replace the comma with a decimal point, hence forcing PHP to interpret the number as 34.7140.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜