How to Get Double Only From String in Flutter

In this example, you will learn how to get the double numbers from a string, previously we have already posted about converting string to double, but this is a different task, here, we will extract a double from an invalid string format. 

String str = "Hafce00453dfg23.4fdksd";
double newdbl = double.parse(str.replaceAll(RegExp(r'[^0-9.]'),''));
print(newdbl);// output: 45323.4

This string is invalid when you directly parse to double, therefore, extract the double-only string from the source string and then double.parse() it.

String str1 = "Hafce00453dfg234fdksd";
double newdbl1 = double.parse(str1.replaceAll(RegExp(r'[^0-9.]'),''));
print(newdbl1);// output: 453234.0

If there is no dot in the string, it will attach one decimal place.

In this way, you can get the double numbers from a string in Dart or Flutter.

No any Comments on this Article


Please Wait...