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

本文翻译自:How do I convert a string to a number in PHP?

I want to convert these types of values, '3' , '2.34' , '0.234343' , etc. to a number. 我想将这些类型的值'3''2.34''0.234343'等转换为数字。 In JavaScript we can use Number() , but is there any similar method available in PHP? 在JavaScript中,我们可以使用Number() ,但是PHP中有可用的类似方法吗?

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

#1楼

参考:https://stackoom.com/question/Zmx6/如何在PHP中将字符串转换为数字


#2楼

Just a little note to the answers that can be useful and safer in some cases. 在某些情况下,仅对可能有用且更安全的答案做一点说明即可。 You may want to check if the string actually contains a valid numeric value first and only then convert it to a numeric type (for example if you have to manipulate data coming from a db that converts ints to strings). 您可能需要先检查字符串是否真正包含有效的数字值,然后才将其转换为数字类型(例如,如果您必须处理来自将整数转换为字符串的db的数据)。 You can use is_numeric() and then floatval() : 您可以使用is_numeric()然后使用floatval()

$a = "whatever"; // any variable

if (is_numeric($a)) 
    var_dump(floatval($a)); // type is float
else 
    var_dump($a); // any type

#3楼

You can change the data type as follows 您可以按以下方式更改数据类型

$number = "1.234";

echo gettype ($number) . "\n"; //Returns string

settype($number , "float");

echo gettype ($number) . "\n"; //Returns float

For historical reasons "double" is returned in case of a float. 由于历史原因,在浮动情况下会返回“ double”。

PHP Documentation PHP文档


#4楼

You can use: 您可以使用:

((int) $var)   ( but in big number it return 2147483647 :-) )

But the best solution is to use: 但是最好的解决方案是使用:

if (is_numeric($var))
    $var = (isset($var)) ? $var : 0;
else
    $var = 0;

Or 要么

if (is_numeric($var))
    $var = (trim($var) == '') ? 0 : $var;
else
    $var = 0;

#5楼

Here is a function I wrote to simplify things for myself: 这是我为简化自己而编写的函数:

It also returns shorthand versions of boolean, integer, double and real. 它还返回布尔,整数,双精度和实数的简写形式。

function type($mixed, $parseNumeric = false)
{        
    if ($parseNumeric && is_numeric($mixed)) {
        //Set type to relevant numeric format
        $mixed += 0;
    }
    $t = gettype($mixed);
    switch($t) {
        case 'boolean': return 'bool'; //shorthand
        case 'integer': return 'int';  //shorthand
        case 'double': case 'real': return 'float'; //equivalent for all intents and purposes
        default: return $t;
    }
}

Calling type with parseNumeric set to true will convert numeric strings before checking type. 将parseNumeric设置为true的调用类型将在检查类型之前转换数字字符串。

Thus: 从而:

type("5", true) will return int type(“ 5”,true)将返回int

type("3.7", true) will return float type(“ 3.7”,true)将返回float

type("500") will return string type(“ 500”)将返回字符串

Just be careful since this is a kind of false checking method and your actual variable will still be a string. 请小心,因为这是一种错误的检查方法,并且您的实际变量仍然是字符串。 You will need to convert the actual variable to the correct type if needed. 如果需要,您将需要将实际变量转换为正确的类型。 I just needed it to check if the database should load an item id or alias, thus not having any unexpected effects since it will be parsed as string at run time anyway. 我只需要它来检查数据库是否应该加载项目ID或别名,因此不会有任何意外的影响,因为无论如何它将在运行时解析为字符串。

Edit 编辑

If you would like to detect if objects are functions add this case to the switch: 如果要检测对象是否为函数,请将这种情况添加到开关中:

case 'object': return is_callable($mixed)?'function':'object';

#6楼

I've found that in JavaScript a simple way to convert a string to a number is to multiply it by 1. It resolves the concatenation problem, because the "+" symbol has multiple uses in JavaScript, while the "*" symbol is purely for mathematical multiplication. 我发现在JavaScript中,将字符串转换为数字的一种简单方法是将其乘以1。它解决了级联问题,因为JavaScript中的“ +”符号有多种用途,而“ *”符号纯粹是用于数学乘法。

Based on what I've seen here regarding PHP automatically being willing to interpret a digit-containing string as a number (and the comments about adding, since in PHP the "+" is purely for mathematical addition), this multiply trick works just fine for PHP, also. 基于我在这里看到的有关PHP自动愿意将包含数字的字符串解释为数字的信息(以及有关加法的注释,因为在PHP中,“ +”纯粹用于数学加法),这种乘法技巧就可以了也适用于PHP。

I have tested it, and it does work... Although depending on how you acquired the string, you might want to apply the trim() function to it, before multiplying by 1. 我已经对其进行了测试,并且可以正常工作...尽管根据获取字符串的方式,您可能需要在将其乘以1之前对其应用trim()函数。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值