try_parse


Description:

public static bool try_parse (string str, out double result = null, out unowned string unparsed = null)

Converts a string to a double value.

This function behaves like the standard strtod() function does in the C locale. It does this without actually changing the current locale, since that would not be thread-safe. A limitation of the implementation is that this function will still accept localized versions of infinities and NANs.

This function is typically used when reading configuration files or other non-user input that should be locale independent. To handle input from the user you should normally use the locale-sensitive system strtod() function.

If the correct value would cause overflow, plus or minus HUGE_VAL is returned (according to the sign of the value), and ERANGE is stored in GLib.errno. If the correct value would cause underflow, zero is returned and ERANGE is stored in GLib.errno.

This function resets errno before calling strtod() so that you can reliably detect overflow and underflow.

Example: String to double, with error detection:

public static int main (string[] args) {
double val;
bool res;

// Output: ``true => 3.444000``
res = double.try_parse ("3.444", out val);
print ("%s => %f\n", res.to_string (), val);

// Output: ``true => -3.444000``
res = double.try_parse ("-3.444", out val);
print ("%s => %f\n", res.to_string (), val);

// Output: ``false => 3.444000``
res = double.try_parse ("3.444d", out val);
print ("%s => %f\n", res.to_string (), val);

// Output: ``false => 0.000000``
res = double.try_parse ("d3.444", out val);
print ("%s => %f\n", res.to_string (), val);

return 0;
}

valac --pkg glib-2.0 double.try_parse.vala

Parameters:

str

the string to convert to a numeric value.

result

the location to store the value

Returns:

true on success, or false.