Rodrigo Vieira
Rodrigo Vieira

Reputation: 3495

How to get number's length in Dart?

How could I get the length of a number in Dart? Is there an equivalent to the one used in strings?

For ex: 1050000 has a length of 7. How could I dynamically discover this?

Upvotes: 15

Views: 12264

Answers (3)

CopsOnRoad
CopsOnRoad

Reputation: 268544

You can try this.

int i = 1050000;

int length = i.toString().length; // 7
// or
int length = '$i'.length; // 7

Upvotes: 27

w461
w461

Reputation: 2698

not precisely the question, but since I found this on my search for getting the magnitude and since I then copied the above answer without thinking:

If you want the magnitude of the number

extension Num on num {
  int length() => this.toInt().toString().length;
}

Upvotes: 1

luisredondo
luisredondo

Reputation: 53

With this extension method you would be able to use the length method on any number.

extension Num on num {
  int length() => this.toString().length;
}

Upvotes: 1

Related Questions