如何添加两个字符串,就好像它们是数字一样? [英] How to add two strings as if they were numbers?

查看:31
本文介绍了如何添加两个字符串,就好像它们是数字一样?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个只包含数字的字符串:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆