Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Integer changes to String

Status
Not open for further replies.

LuckyKoen

Programmer
Feb 14, 2005
57
BE
I have some experience in Java but I am new to JavaScript. What confuses me is that you don't have to declare the type of a variable when defining it. Here is an example of how this is sometimes hard for me to work with :

Code:
function getInt(anInteger) {
	if (anInteger == 10) {
		return anInteger + 5;
	}
	else {
		return anInteger - 5;
	}
}

getInt(10) returns 105
getInt(15) returns 10

Is there a clean way to make sure that anInteger + 5 returns 15 and not 105 ? I use anInteger - 0 + 5 now, but I'd like to know if there is a better way to do it.
 
You can use parseInt to ensure a number is always treated as such:

Code:
var someNum = parseInt(someOtherNum, 10);

The ", 10" tells JS to use decimal (base 10).

Hope this helps,
Dan


[tt]Dan's Page [blue]@[/blue] Code Couch
[/tt]
 
A shorthand technique that I use from time to time forces a string into a number... by subtracting zero the result is cast as a number... so the next operation (a + operation) is then treated as addition rather than concatenation:
Code:
function getInt(anInteger) {
    if (anInteger == 10) {
        return (anInteger - 0) + 5;
    }
    else {
        return anInteger - 5;
    }
}
Of course, parseInt() would do the same (as Dan mentioned above).
Cheers,
Jeff

[tt]Jeff's Page [/tt][tt]@[/tt][tt] Code Couch
[/tt]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top