AlfieWebDevTips Homefor new and experienced developers
[Home Home] [Web Development Web Development ] [Code Generators Code Generators ] [Resources Resources ] [Contact Us Contact ] |WebDevTips Privacy Privacy |
Print This Page

You are here : Home - Resources - FAQ - Javascript Q3

FAQ - Javascript Q3



Q3:How do I change a string into a number?

A:Too cut a long story short :) For whatever reason you have got a number and you want to add or subtract from it. The problem is the number is actually a string. Well, let's give an example.
Look at this code

<script language="JavaScript" type="text/javascript"> 
<!-- 
function test1(){ 
var xyz="2468"; //simulate the number as a string 
answer = xyz+1000; 
alert("The sum is "+xyz"+1000\which should give us 3468"); 
alert("but what we actually get is"+answer); 

// --> 
</script>

click here to test it


Now look at this

<script language="JavaScript" type="text/javascript"> 
<!-- 
function test2(){ 
var xyz="2468"; //simulate the number as a string 
 
xyz -= 0; //the magic bit - 0 
 
answer = xyz+1000; 
alert("The sum is "+xyz+"+1000\nwhich should give us 3468"); 
alert("and what we get is\n"+answer+"\nProblem solved"); 

// --> 
</script>

click here to test it

xyz -= 0; turns a string into a number - it's that easy :)


back to faq




Google
 

[back to top of page]   

[labelled with icra -  - this link will open in a new window] [RSS Content]

[Copyright © WebDevTips]