How to add two strings as if they were numbers?

2018-12-31 03:36发布

I have two strings which contain only numbers:

var num1 = '20',
    num2 = '30.5';

I would have expected that I could add them together, but they are being concatenated instead:

num1 + num2; // = '2030.5'

How can I force these strings to be treated as numbers?

标签: javascript
18条回答
情到深处是孤独
2楼-- · 2018-12-31 04:28

MDN docs for parseInt
MDN docs for parseFloat

In parseInt radix is specified as ten so that we are in base 10. In nonstrict javascript a number prepended with 0 is treated as octal. This would obviously cause problems!

parseInt(num1, 10) + parseInt(num2, 10) //base10
parseFloat(num1) + parseFloat(num2)

Also see ChaosPandion's answer for a useful shortcut using a unary operator. I have set up a fiddle to show the different behaviors.

http://jsfiddle.net/EtX6G/

var ten = '10';
var zero_ten = '010';
var one = '1';
var body = document.getElementsByTagName('body')[0];

Append(parseInt(ten) + parseInt(one));
Append(parseInt(zero_ten) + parseInt(one));
Append(+ten + +one);
Append(+zero_ten + +one);

function Append(text) {
    body.appendChild(document.createTextNode(text));
    body.appendChild(document.createElement('br'));
}
查看更多
唯独是你
3楼-- · 2018-12-31 04:28
var result = Number(num1) + Number(num2);
查看更多
回忆,回不去的记忆
4楼-- · 2018-12-31 04:28

Try this if you are looking for simple Javascript code and want to use two input box and add numbers from the two value. Here's the code.

    Enter the first number: <input type="text" id="num1" /><br />
    Enter the seccond number: <input type="text" id="num2" /><br />
    <input type="button" onclick="call()" value="Add"/>

    <script type="text/javascript">
    function call(){
    var q=parseInt(document.getElementById("num1").value);
    var w=parseInt(document.getElementById("num2").value);
    var result=q+w;
    }
    </script>

for more details please visit http://informativejavascript.blogspot.nl/2012/12/javascript-basics.html

查看更多
冷夜・残月
5楼-- · 2018-12-31 04:31

You may use like this:

var num1 = '20',
    num2 = '30.5';

alert((num1*1) + (num2*1)); //result 50.5

When apply *1 in num1, convert string a number.

if num1 contains a letter or a comma, returns NaN multiplying by 1

if num1 is null, num1 returns 0

kind regards!!!

查看更多
梦醉为红颜
6楼-- · 2018-12-31 04:36

Make sure that you round your final answer to less than 16 decimal places for floats as java script is buggy.

For example 5 - 7.6 = -2.5999999999999996

查看更多
何处买醉
7楼-- · 2018-12-31 04:37

Use the parseFloat method to parse the strings into floating point numbers:

parseFloat(num1) + parseFloat(num2)
查看更多
登录 后发表回答