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

PHP中的字符串可以很容易地转换为数字(float/int/double)。在大多数用例中,由于PHP进行隐式类型转换,所以不需要它。PHP中有许多将字符串转换为数字的方法,下面将讨论其中一些方法:

null

方法1 :使用 number_format()函数 函数用于将字符串转换成数字。成功时返回格式化的数字,否则失败时会发出E_警告。

例子:

<?php
$num = "1000.314" ;
// Convert string in number using
// number_format(), function
echo number_format( $num ), "" ;
// 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 , "" ;
// Type cast using float
echo (float) $num , "" ;
// 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 ), "" ;
// 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, "" ;
// Performing mathematical operation
// to implicitly type conversion
echo $num + 0.0, "" ;
// Performing mathematical operation
// to implicitly type conversion
echo $num + 0.1;
?>


输出:

1000.314
1000.314
1000.414

PHP是一种专门为web开发设计的服务器端脚本语言。通过以下步骤,您可以从头开始学习PHP PHP的教程 PHP示例 .

© 版权声明
THE END
喜欢就支持一下吧
点赞14 分享