如何在 PHP 中分隔数字并获取前两位数字?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7413190/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I separate a number and get the first two digits in PHP?
提问by Jennifer Anthony
How can I separate a number and get the first two digits in PHP?
如何在 PHP 中分隔数字并获取前两位数字?
For example: 1345
-> I want this output=> 13
or 1542
I want 15
.
例如:1345
-> 我想要这个输出 =>13
或者1542
我想要15
.
回答by oezi
one possibility would be to use substr:
一种可能性是使用substr:
echo substr($mynumber, 0, 2);
EDIT:
please not that, like hakresaid, this will break for negative numbers or small numbers with decimal places. his solution is the better one, as he's doing some checks to avoid this.
编辑:
请不要那样,就像hakre说的那样,这将破坏负数或带有小数位的小数。他的解决方案是更好的解决方案,因为他正在做一些检查来避免这种情况。
回答by hakre
First of all you need to normalize your number, because not all numbers in PHP consist of digits only. You might be looking for an integer number:
首先,您需要标准化您的数字,因为并非 PHP 中的所有数字都只包含数字。您可能正在寻找一个整数:
$number = (int) $number;
Problems you can run in here is the range of integer numbers in PHP or rounding issues, see Integers Docs, INF
comes to mind as well.
您可以在这里遇到的问题是 PHP 中的整数范围或舍入问题,请参阅Integers Docs,INF
也会想到。
As the number now is an integer, you can use it in string context and extract the first two characters which will be the first two digits if the number is not negative. If the number is negative, the sign needs to be preserved:
由于数字现在是一个整数,您可以在字符串上下文中使用它并提取前两个字符,如果数字不是负数,这将是前两位数字。如果数字为负,则需要保留符号:
$twoDigits = substr($number, 0, $number < 0 ? 3 : 2);
See the Demo.
见演示。
回答by Spudley
Shouldn't be too hard? A simple substring should do the trick (you can treat numbers as strings in a loosely typed language like PHP).
应该不会太难了吧?一个简单的子字符串应该可以解决问题(您可以将数字视为松散类型语言(如 PHP)中的字符串)。
See the PHP manual page for the substr()
function.
有关该substr()
函数,请参阅 PHP 手册页。
Something like this:
像这样的东西:
$output = substr($input, 0, 2); //get first two characters (digits)
回答by Geoffroy
回答by Adeojo Emmanuel IMM
this should do what you want
这应该做你想做的
$length = 2;
$newstr = substr($string, $lenght);
回答by cenanozen
If you don't want to use substr you can divide your number by 10 until it has 2 digits:
如果您不想使用 substr,您可以将您的数字除以 10,直到它有 2 位数字:
<?php
function foo($i) {
$i = abs((int)$i);
while ($i > 99)
$i = $i / 10;
return $i;
}
will give you first two digits
会给你前两位数字