2

I am bewildered as to why I cannot add three numbers together. Here is my HTML:

<div><label>Sales Price: </label>
    <input type="number" name="sales_price" value="3">
</div>
<div><label>Incentives: </label>
    <input type="number" name="incentives" value="2">
</div>    
<div><label>Acquisition Fee: </label>
    <input type="number" name="acq_fee" value="1">

Here is my JavaScript:

var salesPrice = document.getElementsByName("sales_price")[0];
var incentives = document.getElementsByName("incentives")[0];
var acqFee = document.getElementsByName("acq_fee")[0];

var netCapCost = salesPrice.value - incentives.value + acqFee.value;

I wanted a simple calculation to be done: (3-2+1) = 2. However, netCapCost returns 11, which is the concatenation of the result of (3-2) and 1. What did I do wrong? Many Thanks in advance!

4 Answers 4

2

You need to convert those values into numbers with parseInt() or else the + operator will be interpreted as string concatenation. You are doing

var netCapCost = salesPrice.value - incentives.value + acqFee.value;

Which is

var netCapCost = "3" - "2" + "1"

"3"-"2" will return 1, which is what you want but 1 + "1" will be concatenated into "11" since the right operand is a string. So Number + String -> concatenation

Sign up to request clarification or add additional context in comments.

1 Comment

i don't believe parseInt will be the correct way to go as the price could be (5.95). I believe parseFloat is the better approach
1

var salesPrice;
var incentives;
var acqFee;
var npc;


function calculate(e) {
    var netCapCost = (parseFloat(salesPrice.value) - parseFloat(incentives.value) + parseFloat(acqFee.value)).toPrecision(3);
    npc.value = netCapCost;
}

window.onload = function (){
	
	
salesPrice = document.getElementsByName("sales_price")[0];
incentives = document.getElementsByName("incentives")[0];
acqFee = document.getElementsByName("acq_fee")[0];
npc = document.getElementsByName("npc")[0];
	salesPrice.onchange = calculate;
	calculate();
	
	
};

Your problem is that text fields value is always of type STRING. When subtracting it forces a conversion to type FLOAT. Then the plus operation shares an opperator with the concatenate operation. So when you have two strings being added it concatenates rather than converting to FLOAT or INT. So basically you have "2"-"1" being converted to 2-1 as strings cannot be subtracted which gives you (1) then you have (1)+"1" which will concatenate rather than add as you have a string. Always use parseFloat or parseInt when expecting numeric data from user entry as it will always be a string when originally submitted.

6 Comments

Thank you for the response. I tried using your code but it returned no answer. I tried parseFloat(document.getElementsByName("sales_price")[0].value) as well, since I want to convert the value to a number, but it didn't seem to work either. jsfiddle.net/mademoiselletse/uge2qzqv/1
I have altered my code above. Works in my normal browser but not in JSFiddle as it uses the window.load event. I accidently applied parseFloat to the element object rather than the value.
@Vic removed onLoad from jsfiddle. here you go. jsfiddle.net/pcconsolidated/c39ge74z/2
Just t is food practice to use the onload event to ensure the body is loaded before assigning elements to the variables or it could try to assign it before the element is created.
thank you so much! It works! May I ask why assigning var salesPrice = parseFloat(document.getElementsByName("sales_price")[0].value) would not work?
|
1

you are doing a string concatation, all value get from input value are string,

the first calcuation salesPrice.value - incentives.value is currect is becuase, the - sign convert the incentives.value to number

the currect way is

var netCapCost = parseInt(salesPrice.value, 10) - parseInt(incentives.value, 10) + parseInt(acqFee.value, 10);

it's better to use a Math library to do the calcuation in javascript, because sooner or later, you will encounter the problem like 0.3 - 0.2 = 0.09999999

3 Comments

i don't believe parseInt will be the correct way to go as the price could be (5.95). I believe parseFloat is the better approach
yes, I'm just clearify the main problem in the example code, parseFloat is also not correct when calculate price, as I mentioned, 0.3 - 0.2 !== 0.1
Alright. I have always done with parseFloat().toPrecision(3);
1

I think confusion here is HTML 5 introduces input type number however javascript engine doesn't introduce support for reading such specific fields. We end up using old traditional way of reading input field value which defaults everything to string.

Only advantage of using number type field would be that you do not have to worry about exception/erroneous situation where number is not being entered.

Other answer suggesting to use parseInt function, is the way to go unless you have luxury of introducing javascript framework like jQuery and use more sophisticated approach for reading it.

1 Comment

You still need to worry about validation as many browsers will allow a manual entry of non numbers into number fields.

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.