How to take the units of a two-digit number

Asked

Viewed 1,061 times

1

I need to get the units of a two-digit number with PHP.

example:

$num = 25;
$dig1 = 2;
$dig2 = 5; 
  • You want to sort the numbers by digits, that?

  • I just want to take their unit, the first digit, and the second digit, and create a number by part, as you see in the example

4 answers

3


To get the unit, just calculate the rest of the division by 10:

$num = 25;
echo $num % 10; // Imprime 5

And for the ten, just take the entire part of the division by 10:

$num = 25;
echo intdiv($num, 10); // Imprime 2

The same works for negative values:

$num = -25;
echo intdiv($num, 10) . PHP_EOL; // Imprime -2
echo $num % 10 . PHP_EOL; // Imprime -5

See working on Ideone.

PHP 5

As the function intdiv only introduced in PHP version 7, an alternative to PHP 5 is to use the function round:

echo round($num/10, 0, PHP_ROUND_HALF_DOWN);

The first value refers to the value to be rounded; the second refers to the number of decimal places and the third if it should be rounded down. In this way, I would return 2 to $num = 25 and -2 to $num = -25.

  • the function intdiv() is not working here, it is saying that it does not exist

  • @Ricardoparizsilva, sorry, this function was only introduced in PHP version 7. I will edit the answer with an alternative to PHP 5.

  • All right, thank you

2

In php every string can be considered an array of characters and it is possible to cast from int to string, so you can get the digits of a number like this

In PHP 7

$num = 25;
$dig1 = ((string)abs($num))[0];
$dig2 = ((string)abs($num))[1];

In PHP >= 5.4

$num = 25;
$dig1 = strval(abs($num))[0];
$dig2 = strval(abs($num))[1];
  • There’s also the problem that $num is negative. Position 0 of string would be the sign of least.

  • Really, I think it was not a good solution, I fixed to at least not have this problem

  • for my case it works, since valid if the number is negative before doing operations with it

1

Divide by 10 and take the rest of the division.

$num = 25;
$unidades = 25 % 10; // retorna 5

1

You can use the function str_split() php

$array = str_split($num);
  • If $num is negative, the result loses meaning.

  • If in your case it’s allowed, you can always do the following $array = str_split(abs($num)); So will the Absolute value of $num

  • In this case it would result in 2 and 5 (positive), which mathematically does not make sense. If the input is only positive, it is a solution, but if it can be negative, it is best to do it by mathematical operations.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.