如何将两个字符串作为数字相加? [英] How to add two strings as if they were numbers?
本文介绍了如何将两个字符串作为数字相加?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个只包含数字的字符串:
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?
推荐答案
我会先使用一元加号运算符将它们转换为数字.
I would use the unary plus operator to convert them to numbers first.
+num1 + +num2;
这篇关于如何将两个字符串作为数字相加?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文