Home > Back-end >  i want to get the digits of an int value one by one how can i do
i want to get the digits of an int value one by one how can i do

Time:09-07

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]

CodePudding user response:

Try this:

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

CodePudding user response:

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.

CodePudding user response:

Try This simple method :

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