fromStringOr

Summary

Converts a string to its equivalent double value or the provided default value if the conversion fails.

Usage

public static double fromStringOr(string numberAsStr, double defaultValue)

Returns

The double equivalent of the string value or the provided default value if the string is not a numeric value.

Parameters

numberAsStr

The string value to convert.

defaultValue

The default value to return if the conversion fails.

Description

Converts a string to its equivalent double value or the provided default value if the conversion fails.

import System;

double x = Double.fromStringOr("100", 101);
Console.log(x); // 100 // conversion succeeded
double y = Double.fromStringOr("abc", 101);
Console.log(y); // 101 // conversion failed so default value returned

The default value is also returned if the numeric string value falls outside the range of the double data type (-1.79769313486232e308 to 1.79769313486232e308).

import System;

double tooBig = Double.fromStringOr("1e400", 100);
Console.log(tooBig); // 100

If the Double.NaN (IEEE-754 Not a Number) value is desired, a string value of NaN will return this value and not the specified default value:

import System;

double y = Double.fromStringOr("NaN", 100);
Console.log(y); // Double.NaN

Examples

Basic Usage
1
2
3
4
5
6
import System;
 
double valid = Double.fromStringOr("100", 23);
Console.log(valid); // 100
double invalid = Double.fromStringOr("abc", 24);
Console.log(invalid); // 24

Share

HTML | BBCode | Direct Link