简体   繁体   English

如何将字符串转换为带有“tail”的浮点数?

[英]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"?我不明白为什么是“34”? Why $float is not '34,7140'?为什么 $float 不是'34,7140'?
How can I get $float = 34,7140?我怎样才能得到 $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: PHP(和大多数其他计算机语言)中的小数点分隔符是点,而不是逗号:

Update: floatval() stops parsing the string as soon as it finds a non-numeric character.更新: floatval()一旦找到非数字字符就停止解析字符串。 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.因为“34,7140”是一个字符串,因为它包含一个逗号字符。

You could use $float = floatval(str_replace(',', '', $value[$id]));你可以使用$float = floatval(str_replace(',', '', $value[$id])); to remove the comma character, or $float = floatval(str_replace(',', '.', $value[$id]));删除逗号字符,或$float = floatval(str_replace(',', '.', $value[$id])); to replace the comma with a decimal point, hence forcing PHP to interpret the number as 34.7140.用小数点替换逗号,从而强制 PHP 将数字解释为 34.7140。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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