【问题标题】:PHP Manual: Number Conversion in Is_Numeric Example 1?PHP 手册:Is_Numeric 示例 1 中的数字转换?
【发布时间】:2017-01-20 03:50:24
【问题描述】:

我在 PHP 文档中遇到了这个示例:

<?php
$tests = array(
    "42",
    1337,
    0x539,
    02471,
    0b10100111001,
    1337e0,
    "not numeric",
    array(),
    9.1
);

foreach ($tests as $element) {
    if (is_numeric($element)) {
        echo "'{$element}' is numeric", PHP_EOL;
    } else {
        echo "'{$element}' is NOT numeric", PHP_EOL;
    }
}
?>

输出:

'42' is numeric
'1337' is numeric
'1337' is numeric
'1337' is numeric
'1337' is numeric
'1337' is numeric
'not numeric' is NOT numeric
'Array' is NOT numeric
'9.1' is numeric

“42”之后的五个示例都计算为“1337”。我可以理解为什么'1337e0'(科学记数法)会出现这种情况,但我不明白为什么其他人会出现这种情况。

我在文档的 cmets 中找不到任何人提到它,我也没有在这里找到它,所以任何人都可以解释为什么“0x539”、“02471”和“0b10100111001”都评估为“ 1337'。

【问题讨论】:

    标签: php evaluation isnumeric


    【解决方案1】:

    当输出所有数字时,都会转换为正常表示。这是十进制数系统,非科学记数法(例如1e10 - 科学浮点数)。

    十六进制:

    十六进制数字以0x 开头,后跟任何0-9a-f

    0x539 = 9*16^0 + 3*16^1 + 5*16^2 = 1337
    

    八进制:

    八进制数以0 开头,仅包含整数 0-7。

    02471 = 1*8^0 + 7*8^1 + 4*8^2 + 2*8^3 = 1337
    

    二进制:

    二进制数以0b 开头并包含0s 和/或1s。

    0b10100111001 = 1*2^0 + 1*2^3 + 1*2^4 + 1*2^5 + 1*2^8 + 1*2^10 = 1337
    

    【讨论】:

      【解决方案2】:

      它们是八进制、十六进制和二进制数。

      http://php.net/manual/en/language.types.integer.php

      【讨论】:

        猜你喜欢
        • 2020-06-16
        • 2012-07-20
        • 2019-05-20
        • 1970-01-01
        • 2015-07-30
        • 2015-09-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多