问题
This is a simple dropdown with values. I'm trying to pull the values as currency then add.
The values aren't being added (1+1=2
or 1+2=3
) but instead are concatenating (1+1=11
or 1+2=12
). Where am I going wrong here?:
<script>
function displayResult()
{
var strm=document.getElementById("matt").options[document.getElementById("matt").selectedIndex];
var t=strm.text.search("\\\$");
var strb=document.getElementById("box").options[document.getElementById("box").selectedIndex];
var b=strb.text.search("\\\$");
var x=strm.text.substr(t+1);
var y=strb.text.substr(b+1);
var math= x + y;
alert(strm.text.substr(t+1));
alert(strb.text.substr(b+1));
alert(math);
}
</script>
<form>
Select #1:
<select id="matt">
<option>$1.00</option>
<option>$2.00</option>
</select>
<br />
Select #2:
<select id="box">
<option>$3.00</option>
<option>$4.00</option>
</select>
</form>
<button type="button" onclick="displayResult()">Display index</button>
回答1:
Use parseInt()
to cast your strings as integers.
var math= parseInt(x,10) + parseInt(y,10);
See https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/parseInt
回答2:
To make sure your values are added as numbers, cast them to Number
first:
Number('2') + Number('2') = 4
'2' + '2' = '22'
回答3:
Try using parseFloat() or parseInt().. Otherwise it won't recognize it as a number.. It will append as a normal string..
var math= parseFloat(x) + parseFloat(y);
alert(math)
Check FIDDLE
回答4:
The values are being interpreted as strings, you need to convert them to ints with parseInt prior to adding them.
回答5:
The substring()
function returns the substring of a given string, which is, of course, a string and not an object upon which math can be performed. If you parse those strings into a number, using parseInt()
, then it will work:
var x= parseInt(strm.text.substr(t+1),10);
var y= parseInt(strb.text.substr(b+1),10);
Also, you don't need to keep redeclaring var
, you could instead comma-separated variable declarations:
var x = parseInt(strm.text.substr(t+1),10),
y = parseInt(strb.text.substr(b+1),10);
回答6:
I discovered something interesting today. I was doing the calculator project on theodinproject. I have addition, subtraction, multiplication, and division functions. Subtraction, multiplication, and division works fine without needing to explicitly tell javascript to treat the parameter as a Number.
来源:https://stackoverflow.com/questions/12535285/how-to-add-two-values-in-javascript