Skip to main content

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.

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.