How to Extract Number from String in Dart?

One of the common tasks in programming is to extract number from string. In Dart, there are several ways to achieve this. In this article, we will explore some of the most common methods.

Table of Contents

Extract Int

If you have a string that contains only numbers, you can use the parseInt() function to get the number from it.

String str = "123456"; 
int num = int.parse(str); 
print(num); // 123456

If you have a string that contains both numbers and letters, you can use the RegExp class to match only the numbers in the string.

String str = "182000000 and 2670000. That’s how many seconds I’ve spent thinking.";
String? numStr = RegExp(r"\d+").firstMatch(str)!.group(0);
int num = int.parse(numStr!);
print(num); // 182000000

Extract Double

In order to get double from a string in Dart, you can use the parse method of double type. This method takes a String and returns a double.

String numbers = "123.55";
print(double.parse(numbers)); //123.55
String numbers = "56.20 kg";
double? d = double.tryParse(numbers.replaceAll(RegExp(r'[^0-9\.]'), ''));
print(d); //56.2

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.