11
$\begingroup$

How can we convert a list to an integer correctly?

{5, 22, 4, 5} -> 52245?

When I use the command FromDigits in Mathematica

FromDigits[{5, 22, 4, 5}]

The result is incorrect, namely 7245

$\endgroup$

5 Answers 5

11
$\begingroup$

Here are three ways to do it. The first is the best I think:

FromDigits@Flatten[IntegerDigits /@ {5, 22, 4, 5}]

ToExpression@StringJoin[ToString /@ {5, 22, 4, 5}]

ToExpression@StringJoin@StringCases[Characters@ToString@{5, 22, 4, 5}, DigitCharacter]
$\endgroup$
0
10
$\begingroup$
FromDigits @ ToString @ Row @ {5, 22, 4, 5}

Head[%]
52245

Integer
$\endgroup$
5
$\begingroup$
ToExpression@StringJoin@IntegerString[{5, 22, 4, 5}]

52245

ToExpression@StringJoin@IntegerString[{5, 22, 4, 5},#]&/@{2,10,16}

{10110110100101, 52245, 51645}

$\endgroup$
4
$\begingroup$
{5, 22, 4, 5} ~ StringRiffle ~ "" // FromDigits
52245
$\endgroup$
1
  • 1
    $\begingroup$ Awesome. Never thought of StringRiffle $\endgroup$ May 25, 2021 at 14:25
1
$\begingroup$
list = {5, 22, 4, 5};
FromDigits[StringJoin[IntegerString[list]]]

which gives

52245
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.