### Check if a string converted to a number is actually a number in ActionScript (Flex) and setting scale of a number

An easy way to check if a String is actually a number of not is to actually convert the string to a Number and test if it's NaN.

Flex API reference mentions that the top-level function Number(str) returns NaN if the string passed to the method cannot be converted to a Number.

The problem with this approach is that if you take Number(null) or Number(undefined) or Number(""), all will return 0 and will evaluate to "is a number".

The correct way to do this is shown in following code snippet.

It also sets scale of the converted number to two decimal digits.

public static function getNumberFromString(val:*, scale:uint = 2):* { if ((val === null || StringUtil.trim(val) === "" || isNaN(val)) == false) return setScale(Number(val)).toFixed(scale); else return ""; } public static function setScale(number:Number, scale:uint = 2):Number { scale = Math.pow(10, scale); return (Math.round(number * scale) / scale); }

Flex API reference mentions that the top-level function Number(str) returns NaN if the string passed to the method cannot be converted to a Number.

The problem with this approach is that if you take Number(null) or Number(undefined) or Number(""), all will return 0 and will evaluate to "is a number".

The correct way to do this is shown in following code snippet.

It also sets scale of the converted number to two decimal digits.

public static function getNumberFromString(val:*, scale:uint = 2):* { if ((val === null || StringUtil.trim(val) === "" || isNaN(val)) == false) return setScale(Number(val)).toFixed(scale); else return ""; } public static function setScale(number:Number, scale:uint = 2):Number { scale = Math.pow(10, scale); return (Math.round(number * scale) / scale); }