0

I have the following code which interprets the numbers as strings and adds them like 100300 instead of 400:

var rate = document.getElementById('pur_price').value;
var pprice = document.getElementById('pur_price').value;
var rate1 = document.getElementById('select2').value;
var refurb = 300;
document.getElementById('avg_claim_rate').value=id;
document.getElementById('amount_claim').value=pprice+refurb;

it's the pprice and refurb field, so if pprice=100 and refurb=300, I expect it to show 400, where as at the moment it shows 100300

2
  • 1
    Do you know the difference between PHP and JavaScript? Commented Nov 11, 2014 at 13:54
  • U need to parse the input values with parseFloat before doing calculations with it Commented Nov 11, 2014 at 13:55

4 Answers 4

3

You can use parseInt function:

var pprice = parseInt(document.getElementById('pur_price').value, , 10);
var rate1 = parseInt(document.getElementById('select2').value, , 10);
Sign up to request clarification or add additional context in comments.

Comments

0
var result = +pprice + + refurb;

Comments

0

Use function parseInt() it can be:

document.getElementById('avg_claim_rate').value=id;
document.getElementById('amount_claim').value=parseInt(pprice)+refurb;

Comments

0

As @sergio said, you can use JavaScript's built in parseInt function. Just for reference, you can multiply it by one. JavaScript always converts a string to a number if you multiply it. So you could do something like this:

var num1 = "300";
var num2 = "100";

var num1 = num1 * 1; // Converts string to the number 300
var num2 = num2 * 1;

document.getElementById('number').value = num1+num2;
<input id="number"/>

This is just an alternate way to do the same thing. Use whatever is easiest for you. Hope that helps!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.