How to convert a string to float with “tail”?

2019-07-21 07:19发布

问题:


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 ?

回答1:

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


回答2:

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);
}


回答3:

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.