Mehmet Ali Kara
Mehmet Ali Kara

Reputation: 39

i want to get the digits of an int value one by one how can i do

I want to take the digits of an int number and add them to the list one by one, how can I do

for example int x=1993; Result=[1,9,9,3]

another example int y=32 Result=[3,2]

Upvotes: -1

Views: 755

Answers (3)

Christopher Moore
Christopher Moore

Reputation: 17143

Use modulo for the most efficient implementation:

int x = 1993;
List<int> xList = [];

while(x > 0) {
    xList.add(x % 10);
    x = x ~/ 10;
}
xList = xList.reversed.toList();

print(xList);

This method takes the modulo 10 of the number to get the ones digit and adds it to a list. It then divides by 10 to shift the digits to the right. Since the digits were added in the reverse order of what you want, the list is reversed at the end.

Upvotes: 1

Kishan
Kishan

Reputation: 465

Try This simple method :

int x = 123456
var data = x.toString().split('');
print(data);

Upvotes: 0

Robert Sandberg
Robert Sandberg

Reputation: 8607

Try this:

int yourNumber = 1234;
final yourInts = yourNumber.toString().split('').map((element) => int.parse(element)).toList();
print(yourInts);

Upvotes: 1

Related Questions