在 PHP 中将字符串转换为浮点数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22523003/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 16:04:44  来源:igfitidea点击:

Convert string to float in PHP

phpstringdoubledecimal

提问by user3440366

I have a string value like this "0.00050722" and I want to convert its data type to double/float.

我有一个像 "0.00050722" 这样的字符串值,我想将它的数据类型转换为double/float

I've been trying floatval()and doubleval()but it always returns me a value of 0.

我一直在尝试floatval()doubleval()但它总是返回 0 的值。

I need to get the exact of amount of 0.00050722 in a float datatype.

我需要在浮点数据类型中获得 0.00050722 的确切数量。

回答by hoss

You just need to (typecast)to the desired type

您只需要到(typecast)所需的类型

    <?php
    $string = "0.00050722";
    $float = (float) $string;
    $float2 = $string + 0.0; //this works as well.
    $floatval = floatval($string);
    $double = (double) $string;

    // TEST
    printf("string:   %s - %d<br>", $string, is_float ($string));
    printf("float :   %g - %d<br>", $float, is_float ($float));
    printf("float2:   %g - %d<br>", $float2, is_float ($float2));
    printf("floatval: %g - %d<br>", $floatval, is_float($floatval));
    printf("double:   %g - %d<br>", $string, is_double ($double));

?>

Should result in:

应该导致:

string:   0.00050722 - 0
float :   0.00050722 - 1
float2:   0.00050722 - 1
floatval: 0.00050722 - 1
double:   0.00050722 - 1

Notice that concatenation also works.

请注意,串联也有效。

回答by Dexter

it's work's for me try this

这对我有用 试试这个

<?php
    $string = "0.00050722";
    $num = floatval($string);
    echo $num;   // output 0.00050722
?>

回答by lucacld

For a project I tryed to write this function that convert a string like .087 0.87 1.000,87 to a float:

对于一个项目,我尝试编写此函数将 .087 0.87 1.000,87 之类的字符串转换为浮点数:

public function convertistr2float($string_number){
   $trovavirgola = str_replace(',', '.', $string_number);
   $trovavirgola = explode('.', $trovavirgola);
   //print_r($trovavirgola);
   $int='';
      if(count($trovavirgola)>1){          
        for($i=0;$i<count($trovavirgola);$i++){            
          if((count($trovavirgola)-1)>=0){
            if($i==(count($trovavirgola)-1)){
               break;  
             }else{
              $int .= $trovavirgola[$i];
             }
          }
      }//for
      $decimale = end($trovavirgola) ;
    if($decimale==''){$decimale=0;}
    if($int==''){$int=0;}
  $number= $int.'.'.$decimale;
} else{
  $number=  $trovavirgola[0]; 
}
$number = floatval($number);
 return $number;

}//convertistr2float

}//convertistr2float