Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.

1. ## JavaScript fails to add properly, adds as if strings are present?

Sorry for my beginner question but I am having some trouble getting this to work. I am trying to create a simple I=PRT calculator so it can calculate interest. But when you run it it adds the digits. Ex. 5+100=5100 instead of 105. Give it a try. My code is bellow.[CODE]

// JavaScript Document
alert("This is a simple calculator which will allow you to calculate the interest on a principle.");

var principle = prompt("What is the amount you would like to calculate interest for?");

var rate = prompt("What is the interest rate. eg. For 3.9% write 3.9");

var term = prompt("How long in the period under calculation going to be? eg. For 1 year write 1");

var interest = principle*(rate/100)*term;

var result = principle + interest;

var a = "This means the interest is going to be \$";

var b = " And the total to be paid is \$";

var c = a + interest + b + result;

[CODE]

2. If ANY variable is a string, then the + of the intended math is treated as concatenation.

You could try:
Code:
```var c = Number(a) + Number(interest) + Number(b) + (Number(principle) + Number(interest));

// or
var result = (principle*1) + (interest*1);
var c = (a*1) + (interest*1) + (b*1) + result;

// or a few other variations on the theme
// parseFloat() or parseInt() come to mind.```

3. ## Users who have thanked jmrker for this post:

tanayp5 (10-26-2011)

4. Originally Posted by jmrker
If ANY variable is a string, then the + of the intended math is treated as concatenation.

You could try:
Code:
```var c = Number(a) + Number(interest) + Number(b) + (Number(principle) + Number(interest));

// or
var result = (principle*1) + (interest*1);
var c = (a*1) + (interest*1) + (b*1) + result;

// or a few other variations on the theme
// parseFloat() or parseInt() come to mind.```
Thanks so much for your help, I got it to work right away. By the way, if possible can you please simplify what you did to help me solve the problem.

5. Originally Posted by tanayp5
Thanks so much for your help, I got it to work right away. By the way, if possible can you please simplify what you did to help me solve the problem.
Which one?

6. principle != principal

7. Originally Posted by Philip M
principle != principal
You can stand on your principle while others will take no interest in your principal.

8. Keep you hands off my principal!