fromStringOr

Summary

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

Usage

public static int fromStringOr(string numberAsStr, int defaultValue)

Returns

The int equivalent of the string value or the provided default value if the string is not valid.

Parameters

numberAsStr

The string value to convert.

defaultValue

The default value to return if the conversion fails.

Description

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

import System;

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

If the string being converted is numeric but does not fit into the int data range [ -2147483648, 2147483647 ] (inclusive), the default value will be returned.

import System;

int fits = Integer32.fromStringOr("2147483647", 1);
Console.log(fits); // 2147483647
int exceedByOne = Integer32.fromStringOr("2147483648", 100);
Console.log(exceedByOne); // 100
int exceedByTwo = Integer32.fromStringOr("2147483649", 100);
Console.log(exceedByTwo); // 100
int exceedByThree = Integer32.fromStringOr("2147483650", 100);
Console.log(exceedByThree); // 100

Examples

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

Share

HTML | BBCode | Direct Link