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

2021-12-31 00:00:00 type-conversion casting php

我想将这些类型的值,'3''2.34''0.234343'等转换成数字.在 JavaScript 中我们可以使用 Number(),但在 PHP 中是否有类似的方法?

I want to convert these types of values, '3', '2.34', '0.234343', etc. to a number. In JavaScript we can use Number(), but is there any similar method available in PHP?

Input             Output
'2'               2
'2.34'            2.34
'0.3454545'       0.3454545

推荐答案

有以下几种方法:

  1. 将字符串转换为数字原始数据类型:

  1. Cast the strings to numeric primitive data types:

$num = (int) "10";
$num = (double) "10.12"; // same as (float) "10.12";

  • 对字符串进行数学运算:

  • Perform math operations on the strings:

    $num = "10" + 1;
    $num = floor("10.1");
    

  • 使用 intval()floatval():

    $num = intval("10");
    $num = floatval("10.1");
    

  • 使用settype().

  • 相关文章