Click to See Complete Forum and Search --> : How to convert a string/char to an int?


ashas
09-29-2003, 02:05 AM
Hi,

I have auser entering in an integer value via a web form, I need to convert that value to an int so that I can increment it and store it..

Is there a method in Javascript for converting a char/string to an int?


Thanks,
Asha

lillu
09-29-2003, 02:18 AM
Try the parseInt function.

variable = parseInt(variable);

However, javascript is a friendly loosely-typed language and if you use math operations on strings it will assume that you actually mean numbers.... but I'd rather be on the safe side and explicitly tell javascript which data type I'm currenty using...

Xin
09-29-2003, 02:42 PM
you might want to use parseFloat() instead, parseInt("08") will give you something wrong instead of 8.

steelersfan88
04-01-2004, 02:51 PM
Using that method, try:variable = parseInt(parseFloat("010.6"))or to avoid the parseInt alltogether, try:
<script type="text/javascript">

var num = "010.6"
num = (parseFloat(parseFloat(num).toString().substr(0,(parseFloat(num).toString().indexOf('.') > -1) ? (parseFloat(num).toString().indexOf('.')) : (parseFloat(num).toString().length))))
alert(num)

</script>It takes the string, makes in a number, then makes it a string, finds any period, cuts off the decimal, then returns back as a number. The first method simply makes the string a floating point decimal before converting to an integer :)

Juuitchan
04-01-2004, 05:50 PM
Oh no. Try this on .00000007 to see one thing wrong with it.

I've read that explicitly specifying base 10 will make parseInt work correctly.

Juuitchan
04-01-2004, 06:00 PM
Lillu:

Only sometimes are strings treated like numbers in math operations.

Examples:

"5"+"2" is "52"

"5"-"2" is 3 (or is it "3"? I'm not sure)

steelersfan88
04-01-2004, 06:17 PM
Giving that number just displays it in scientific notation. You could do a check to see if its less than one 1, then do it, such as:<script type="text/javascript">

var num = "-.000007"
num = (num < 1 && num > -1) ? 0 : (parseFloat(parseFloat(num).toString().substr(0,(parseFloat(num).toString().indexOf('.') > -1) ? (parseFloat(num).toString().indexOf('.')) : (parseFloat(num).toString().length))))
alert(num)

</script>.

Strings are treated as numbers only when not using the plus operator, since it is also the concatenation operator. Other languages intelligently use the ampersand as the concatenation character to avoid this problem. "5"-"2" = 3; tested below:<script type="text/javascript">

alert(("5"-"2")==="3") // false
alert(("5"-"2")===3) // true

</script>To do the base 10 thing, place as: parseInt(num,10). That should do the trick :)