Number Parsing in D Programming Language
Parsing numbers from strings is a basic but common task in many programs; here’s how to do it in D.
import std.stdio;
import std.conv;
void main() {
// With to!double, we parse the string to a double-precision floating-point number.
double f = to!double("1.234");
writeln(f);
// For parsing integers, we use to!long. The base is inferred from the string.
long i = to!long("123");
writeln(i);
// to!long will recognize hex-formatted numbers.
long d = to!long("0x1c8", 16);
writeln(d);
// For unsigned integers, we use to!ulong.
ulong u = to!ulong("789");
writeln(u);
// to!int is a convenience function for basic base-10 int parsing.
int k = to!int("135");
writeln(k);
// Parse functions throw an exception on bad input.
try {
int j = to!int("wat");
} catch (ConvException e) {
writeln(e.msg);
}
}
To run the program, save it as number_parsing.d
and use the D compiler:
$ dmd number_parsing.d
$ ./number_parsing
1.234
123
456
789
135
std.conv.ConvException: Unexpected 'w' when converting from type string to type int
In D, we use the std.conv
module for number parsing. The to
template function is a powerful tool that can convert between various types, including parsing strings to numbers.
For floating-point numbers, we use to!double
. For integers, we use to!long
for signed integers and to!ulong
for unsigned integers. The base of the number is automatically inferred from the string, but can be explicitly specified as a second argument to to
.
Unlike in some other languages, D’s to
function will throw a ConvException
when it encounters invalid input, rather than returning an error value. This allows for more robust error handling using try-catch blocks.
Next, we’ll look at another common parsing task: URLs.