Integer Parsing in JavaScript


Integer Parsing in JavaScript. Some utility methods and tips

First Question will be like: How do I convert strings to numbers in JavaScript?

Answer: To convert a string to a number, use the JavaScript function parseFloat (for conversion to a floating-point number) or parseInt (for conversion to an integer).

parseFloat syntax: parseFloat('string')

How it works:

The argument of
parseFloat must be a string or a string expression. The result of parseFloat is the number whose decimal representation was contained in that string (or the number found in the beginning of the string). If the string argument cannot be parsed as a decimal number, the results will be different in different browsers (either 0 or NaN).

Examples (comments in each line give the conversion results):

parseFloat(‘1.45kg’)  // 1.45
parseFloat(‘77.3’)    // 77.3
parseFloat(‘077.3’)   // 77.3
parseFloat(‘0x77.3’)  // 0
parseFloat(‘.3’)      // 0.3
parseFloat(‘0.1e6’)   // 100000

parseInt syntax: parseInt( 'string' [, base] )

How it works:

The first argument of parseInt must be a string or a string expression. The result returned by parseInt is an integer whose representation was contained in that string (or the integer found in the beginning of the string). The second argument (base), if present, specifies the base (radix) of the number whose string representation is contained in the string. The base argument can be any integer from 2 to 36.

 

If there is only one argument, the number base is detected according to the general JavaScript syntax for numbers. Strings that begin with 0x or -0x are parsed as hexadecimals; strings that begin with 0 or -0 are parsed as octal numbers. All other strings are parsed as decimal numbers.

If the string argument cannot be parsed as an integer, the results will be different in different browsers (either 0 or NaN).

 

Examples (comments in each line give the conversion results):

parseInt(‘123.45’)  // 123
parseInt(’77’)      // 77
parseInt(‘077’,10)  // 77
parseInt(’77’,8)    // 63  (= 7 + 7*8)
parseInt(‘077’)     // 63  (= 7 + 7*8)
parseInt(’77’,16)   // 119 (= 7 + 7*16)
parseInt(‘0x77’)    // 119 (= 7 + 7*16)
parseInt(‘099’)     // 0 (9 is not an octal digit)
parseInt(’99’,8)    // 0 or NaN, depending on the platform
parseInt(‘0.1e6’)   // 0
parseInt(‘ZZ’,36)   // 1295 (= 35 + 35*36)

So, if you try with “08” or “09” in parseInt(“value”), you may notice a strange thing: it treats “08” or “09” as 0.

This happens for all invalid inputs. The answer to this question lies in above examples.

An integer can be represented in three different ways: in base 8 (octal), base 10 (decimal) and base 16 (hexadecimal). A starting zero indicates an octal number, which can be anything from 0 to 7 but not 8 or 9. Similarly, a starting “0x” followed by a number that can indicates a hexadecimal number which can be anything from 0 to F.

The solution to the problem is very simple. Since “08” means an octal number because of a starting 0, parseInt returns a zero for 8. Now, parseInt accepts a second optional parameter, which is the base of the number. You can forcefully tell it to treat the number as a decimal one by sending a second parameter 10.

Var _num = “08”; //or you can take input from a Form.

var theNumber = parseInt (_num, 10);

A utility method to check if the value is integer or not
[like
int.TryParse Method in .NET]

It makes it really convenient when evaluating a string value as an integer. But, JavaScript has no equivalent so you need to do your own evaluation every time.

Here’s a simple JavaScript method, which I found in the Internet:

function TryParseInt(str,defaultValue){

var retValue = defaultValue;

if(typeof str != ‘undefined’ && str!=null && str.length>0){

        if (!isNaN(str)){

               retValue = parseInt(str);

         }

}

return retValue;

}

The first parameter of the TryParseInt method is the string you want to evaluate, and the second parameter is the default value to return if the string cannot be evaluated to an integer.

Here are some example usages:

//This will return 7

var a = TryParseInt(“7”, 0);

alert(a);

//This will return 0

var b = TryParseInt(“6c”, 0);

alert(b);

//This will return null

var c = TryParseInt(“abcd”, null);

alert(c);

An alternative to this above TryParseInt method will be :

// Returns true if the argument is a valid Integer,

//else returns false.

function isInteger (value)    {      

var i;


if (isEmpty(value)) return false;
 

for (i = 0; i < value.length; i++)      
{

         var c = value.charAt(i); 
         if (false == isDigit(c))
                  return false;
      
 }
 return true;   
}
 

 //Checks if the input string is empty or not

function isEmpty(value)   
{
      
     return ((typeof value == ‘undefined’) || (value == null) || (value.length == 0));   
}

//Checks if the input character is a digit or not 

function isDigit (c)    {      
     return ((c >= “0”) && (c <= “9”));
   

 }

Hope this article helps you [:D]

Advertisements

Javascript Decimals and Significant digits


One of the most common tasks is to format a number for currency display- an integer followed by two decimals.
You may be tempted to use number rounding to first shift the number’s decimal places (via multiplication), round it, then shift the decimal back (via division) to pound the number into your hard earned dollar, though that won’t work in many cases.
For example, consider the number 120. Number rounding certainly won’t get you to 120.00.

To easily format numbers for a specific number of trailing decimals or total digits (aka padding), JavaScript 1.5 introduces the below two methods:
 

Methods                      Description                                                                            

Number.toFixed(x)              Formats any number for “x” number of trailing decimals.
                                           The number is rounded up, and “0”s are used after the decimal point
                                           if needed to create the desired decimal length.

Number.toPrecision(x)        Formats any number so it is of “x” length. Also called significant digits.
                                           A decimal point and “0”s are used if needed to create the desired length

Number.toFixed()

The best way to see all the subtleties of toFixed() is to see it in action:

var dummyNumber=2489.8237
dummyNumber.toFixed(3) //returns 2489.824 (round up)
dummyNumber.toFixed(2) //returns 2489.82
dummyNumber.toFixed(7) //returns 2489.8237000 (padding)

Displaying any number in currency format can’t get any easier!

Number.toPrecision()

To toPrecision() now:

var dummyNumber=123.45
dummyNumber.toPrecision(6) //returns 123.450 (padding)
dummyNumber.toPrecision(4) //returns 123.5 (round up)
dummyNumber.toPrecision(2) //returns 1.2e+2 (you figure it out!)

toPrecision() is useful if your number must be of a certain length.

Browser considerations

Now, as noted, our two heros above are JavaScript 1.5 methods. What this means is that they’ll only work in IE5.5+ and NS6+. The issue of legacy browsers not performing the desired formatting operation not withstanding, how do you ensure that these two methods at least degrade well? Well, by using method detection in your code. For example:

var dummyNumber=2489.8237
if (dummyNumber.toFixed) //if browser supports toFixed() method
dummyNumber.toFixed(2)

Taken From JavaScript Kit