如何在PHP中将字符串转换为数字?

2021年3月28日15:50:09 发表评论 782 次浏览

PHP中的字符串可以很容易地转换为数字(浮点数/整数/双精度数)。在大多数情况下, 由于PHP会进行隐式类型转换, 因此不需要。在PHP中有很多将字符串转换为数字的方法, 下面讨论其中的一些方法:

方法1:使用number_format()函数。 number_format()函数用于将字符串转换为数字。成功时返回格式化的数字, 否则返回E_WARNING。

例子:

<?php
  
$num = "1000.314" ;
  
// Convert string in number using 
// number_format(), function
echo number_format( $num ), "\n" ;
  
// Convert string in number using 
// number_format(), function
echo number_format( $num , 2);
?>

输出如下:

1, 000
1, 000.31

方法2:使用类型转换:类型转换可以将字符串直接转换为float, double或integer原始类型。这是无需任何功能即可将字符串转换为数字的最佳方法。

例子:

<?php
  
// Number in string format
$num = "1000.314" ;
  
// Type cast using int
echo (int) $num , "\n" ;
  
// Type cast using float
echo (float) $num , "\n" ;
  
// Type cast using double
echo (double) $num ;
?>

输出如下:

1000
1000.314
1000.314

方法3:使用intval()和floatval()功能。 intval()和floatval()函数还可用于将字符串分别转换为其相应的整数和浮点值。

例子:

<?php
  
// Number in string format
$num = "1000.314" ;
  
// intval() function to convert 
// string into integer
echo intval ( $num ), "\n" ;
  
// floatval() function to convert
// string to float
echo floatval ( $num );
?>

输出如下:

1000
1000.314

方法4:通过加0或执行数学运算。通过将字符串加0, 也可以将字符串号转换为整数或浮点数。在PHP中, 执行数学运算时, 字符串将隐式转换为整数或浮点数。

<?php
      
// Number into string format
$num = "1000.314" ;
  
// Performing mathematical operation 
// to implicitly type conversion
echo $num + 0, "\n" ;
  
// Performing mathematical operation 
// to implicitly type conversion
echo $num + 0.0, "\n" ;
  
// Performing mathematical operation 
// to implicitly type conversion
echo $num + 0.1;
?>

输出如下:

1000.314
1000.314
1000.414

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: