如何在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()函數。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章