简体   繁体   中英

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM