Using parseInt() and parseFloat() in JavaScript to convert data types to Numbers

By: Nicholas C. Zakas Emailed: 1730 times Printed: 2341 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

JavaScript provides two methods for converting non-number primitives into numbers: parseInt() and parseFloat() . As you may have guessed, the former converts a value into an integer whereas the latter converts a value into a floating-point number. These methods only work properly when called on strings; all other types return NaN .

Both parseInt() and parseFloat() look at a string carefully before deciding what its numeric value should be. The parseInt() method starts with the character in position 0 and determines if this is a valid number; if it isn’t, the method returns NaN and doesn’t continue. If, however, the number is valid, the method goes on to the character in position 1 and does the same test. This process continues until a character isn’t a valid number, at which point parseInt() takes the string (up to that point) and converts it into a number. For example, if you want to convert the string “1234blue” to an integer, parseInt() would return a value of 1234 because it stops processing one it reaches the character b .

Any number literal contained in a string is also converted correctly, so the string “0xA” is properly converted into the number 10. However, the string “22.5” will be converted to 22 , because the decimal point is an invalid character for an integer. Some examples:

var iNum1 = parseInt(“1234blue”); //returns 1234

var iNum2 = parseInt(“0xA”); //returns 10

var iNum3 = parseInt(“22.5”); //returns 22

var iNum4 = parseInt(“blue”); //returns NaN

The parseInt() method also has a radix mode, allowing you to convert strings in binary, octal, hexadecimal, or any other base into an integer. The radix is specified as a second argument to parseInt() , so a call to parse a hexadecimal value looks like this:

var iNum1 = parseInt(“AF”, 16); //returns 175

Of course, this can also be done for binary, octal, and even decimal (which is the default mode):

var iNum1 = parseInt(“10”, 2); //returns 2

var iNum2 = parseInt(“10”, 8); //returns 8

var iNum2 = parseInt(“10”, 10); //returns 10

If decimal numbers contain a leading zero, it’s always best to specify the radix as 10 so that you won’t accidentally end up with an octal value. For example:

var iNum1 = parseInt(“010”); //returns 8

var iNum2 = parseInt(“010”, 8); //returns 8

var iNum3 = parseInt(“010”, 10); //returns 10

In this code, both lines are parsing the string “010” into a number. The first line thinks that the string is an octal value and parses it the same way as the second line (which specifies the radix as 8). The last line specifies a radix of 10, so iNum3 ends up equal to 10.

The parseFloat() method works in a similar way to parseInt() , looking at each character starting in position 0. It also continues until the first invalid character and then converts the string it has seen up to that point. For this method, however, the decimal point is a valid character the first time it appears. If two decimal points are present, the second is considered invalid and the parseFloat() method converts the string up until that position. This means that the string “22.34.5” will be parsed into 22.34 .

Another difference when using parseFloat() is that the string must represent a floating-point number in decimal form, not octal or hexadecimal. This method ignores leading zeros, so the octal number 0908 will be parsed into 908 , and the hexadecimal number 0xA will return NaN because x isn’t a valid character for a floating-point number. There is also no radix mode for parseFloat() .

Some examples of using parseFloat() :

var fNum1 = parseFloat(“1234blue”); //returns 1234.0

var fNum2 = parseFloat(“0xA”); //returns NaN

var fNum3 = parseFloat(“22.5”); //returns 22.5

var fNum4 = parseFloat(“22.34.5”); //returns 22.34

var fNum5 = parseFloat(“0908”); //returns 908

var fNum6 = parseFloat(“blue”); //returns NaN


Javascript Home | All Javascript Tutorials | Latest Javascript Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(4)


1. View Comment

int iNum2 = parseInt(â0xAâ); //returns 10

Why do I get a "Numeric Format Exception on your example above?
int gs = Integer.parseInt("0xA");
Without the "Integer." I get a IDE Editor error.

Doug Whitehead


View Tutorial          By: Doug Whitehead at 2008-12-01 21:27:55
2. View Comment

Hi Doug,

This code is for Javascript, not for Java. Are you trying the code in Java?


View Tutorial          By: Ramlak at 2008-12-04 02:47:44
3. View Comment

Hey,

I am having a peculiar problem with getting an integer from an ajax response. Whenever I call the following code, parseInt(data) returns NaN despite data being a string.
function(data) //return information back from jQuery's get request
{

$('#progress_container').fadeIn(100); //fade in progress bar
$('#progress_bar').width(data +"%"); //set width of progress bar based on the $status value (set at the top of this page)
$('#progress_completed').html(parseInt(data) +"%"); //display the % completed within the progress bar
}


View Tutorial          By: mehr at 2011-05-11 10:22:46
4. View Comment

Thanks

View Tutorial          By: Cecilia at 2012-08-07 05:05:51

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Nicholas C. Zakas
call() and apply() methods in Javascript
this keyword sample in Javascript
Math object and Math functions in Javascript
Using parseInt() and parseFloat() in JavaScript to convert data types to Numbers
Using toString() in JavaScript to convert data types to String
Javascript Basics
History and evolution of Javascript

More Tutorials in Javascript
Use WinSCP to transfer log files remotely using Javascript
Verifying user input in JavaScript
Pause execution in JavaScript
Javascript to display client date and time on webpage
Getting Browser's height and width using Javascript
Highlighting text on a page using CSS
Using revealTrans to do page transitions in Javascript
Password protect a web page using Javascript
Diabling Right Click option in a browser using Javascript
Scrolling message on the status bar using Javascript
window.frames[i] in Javascript
Form validation using Javascript
Using && in Javascript
The if statement in Javascript
do-while, while, for and for-in loops in Javascript

More Latest News
Most Viewed Articles (in Javascript )
Typecasting in Javascript
Using parseInt() and parseFloat() in JavaScript to convert data types to Numbers
Bitwise NOT, AND, OR, XOR operators in Javascript
Javascript Basics
Using toString() in JavaScript to convert data types to String
Show how many characters remaining in a html text box using javascript
List of Keywords and reverved words in Javascript
History and evolution of Javascript
Using ! and !! in Javascript
Using && in Javascript
Password protect a web page using Javascript
Verifying user input in JavaScript
Pause execution in JavaScript
Use WinSCP to transfer log files remotely using Javascript
Click to remove an element from a select html form using javascript
Most Emailed Articles (in Javascript)
Password protect a web page using Javascript
Show how many characters remaining in a html text box using javascript
Javascript Basics
Using parseInt() and parseFloat() in JavaScript to convert data types to Numbers
Using ! and !! in Javascript
switch in Javascript
window.frames[i] in Javascript
Form validation using Javascript
Using revealTrans to do page transitions in Javascript
Scrolling message on the status bar using Javascript
Use WinSCP to transfer log files remotely using Javascript
Click to remove an element from a select html form using javascript
History and evolution of Javascript
List of Keywords and reverved words in Javascript
Typecasting in Javascript