在JavaScript中正确添加两个数字 [英] Adding two numbers in JavaScript incorrectly

查看:139
本文介绍了在JavaScript中正确添加两个数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Global.alert("base: " + base + ", upfront: " + upfront + ", both: " + (base + upfront));

上面的代码输出如下:

base: 15000, upfront: 36, both: 1500036

为什么要加入这两个数字而不是将它们相加?

Why is it joining the two numbers instead of adding them up?

我最终想用另一个字段的值设置为此数量:

I eventually want to set the value of another field to this amount using this:

mainPanel.feesPanel.initialLoanAmount.setValue(Ext.util.Format.number((base + upfront), '$0,000.00'));

当我尝试时,它将数字变成数百万而不是15,036.00。为什么?

And when I try that, it turns the number into the millions instead of 15,036.00. Why?

推荐答案

这可能是因为它们是字符串。尝试解析它们:

This might happen because they are strings. Try parsing them:

Global.alert(
    "base: " + base + ", upfront: " + upfront + ", both: " + 
    (parseInt(base) + parseInt(upfront))
);

如果这些数字是小数,则需要 parseFloat 方法而不是。

If those numbers are decimal you will need the parseFloat method instead.

这篇关于在JavaScript中正确添加两个数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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