前缀零更改数字加法输出 [英] Prefix zero changes output in number addition
本文介绍了前缀零更改数字加法输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图在Javascript中添加两个数字:
I tried to add two numbers in Javascript:
var output;
output = parseInt(a)+parseInt(b);
alert(output);
它给出错误的 output
值,例如如果 a = 015
和 b = 05
.为什么会这样呢?以上示例的预期结果应为20.
It gives wrong output
value, e.g. if a = 015
, and b = 05
. Why is this so?
Expected result of above example should be 20.
推荐答案
如果在数字前加上 0
作为前缀,则要在基数8中进行指定. 015
为因此为13,总和为18.
If you prefix your numbers with 0
, you're specifying them in base 8. 015
is therefore 13, and the sum is 18.
使用第二个 parseInt
参数来强制设置基数:
Use the second parseInt
argument to force a base:
var a = '015', b = '05';
var output;
output = parseInt(a, 10) + parseInt(b, 10);
alert(output); // alerts 20
这篇关于前缀零更改数字加法输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文