# Dart Convert String to int with default value on failure

There are some cases in which a string needs to be converted to int/double. How can we do it in Dart?

We can use these 3 methods depending on the data type.

int.parse(value);
double.parse(value);
num.parse(value);

It is very easy to use. We just give a string to the argument. However, if the string can’t be converted, it throws an error. For this reason, I create the following function in order not to write try-catch many times.

void disp(int Function() cb) {
try {
final result = cb();
print(result);
} catch (e) {
print(e);
}
}

cb() will be replaced with actual method call like int.parse("123"). Let’s see the following example.

disp(() => int.parse("123")); // 123
// FormatException: Invalid radix-10 number (at character 1)
disp(() => int.parse("FC"));

The first one parses the string correctly but the second one fails the conversion and throws an error. The string “FC” is HEX value, so we should actually be able to convert it to int.

## Parse HEX string value

parse method has optional parameter radix. If we give 16 to this parameter, it can parse the HEX value correctly.

disp(() => int.parse("FC", radix: 16)); // 252

The range is 2 – 36. It means that it can convert 0-9 and a-z included string too!!

// FormatException: Invalid radix-10 number (at character 1)
disp(() => int.parse("hogeZ"));
disp(() => int.parse("hogeZ", radix: 36)); // 29694491

I have no idea when to use it though.

## Set default value on parsing Failure

As described above, parsing can fail when the string is not an expected value. We might want to have a default value in this case. We can set it in this way.

// Not recommended
int.parse("hoge", onError: (_) => 0); // 0

Another optional parameter onError requires a callback which is called with an input string argument. We can write a log for example and then return a default value.

However, this is deprecated and thus not recommended using it. The alternative way is the following.

int.tryParse("hoge") ?? 0

tryParse method returns null if the string can’t be converted. Then, we can use double question marks ?? called null-aware operator. If the expression on the left side is null, the value on the right side is used. 0 is returned in this case because “hoge” can’t be converted.