简体   繁体   English

如何在 PHP 中分隔数字并获取前两位数字?

[英]How can I separate a number and get the first two digits in PHP?

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 -> I want this output=> 13 or 1542 I want 15

one possibility would be to use substr :一种可能性是使用substr

echo substr($mynumber, 0, 2);

EDIT:编辑:
please not that, like hakre said, this will break for negative numbers or small numbers with decimal places.请不要那样,就像hakre所说的那样,对于负数或带有小数位的小数,这会中断。 his solution is the better one, as he's doing some checks to avoid this.他的解决方案是更好的解决方案,因为他正在做一些检查来避免这种情况。

First of all you need to normalize your number, because not all numbers in PHP consist of digits only.首先,您需要标准化您的数字,因为并非 PHP 中的所有数字都只包含数字。 You might be looking for an integer number:您可能正在寻找一个整数:

$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 .演示

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)

您可以获取数字的字符串值,然后使用substr获取您想要的部分。

this should do what you want这应该做你想做的

$length = 2;
$newstr = substr($string, $lenght);

With strong type-hinting in new version of PHP (> PHP 7.3) you can't use substr on a function if you have integer or float.在新版本的 PHP (> PHP 7.3) 中使用强类型提示,如果您有整数或浮点数,则不能在函数上使用substr Yes, you can cast as string but it's not a good solution.是的,您可以将其转换为字符串,但这不是一个好的解决方案。 You can divide by some ten factor and recast to int.您可以除以大约十个因子并重新转换为 int。

$number = 1345; 
$mynumber = (int)($number/100);
echo $mynumber;

Display: 13显示:13

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会给你前两位数字

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM