前缀零会在数量增加时更改输出

时间:2012-02-04 08:54:52

标签: javascript

我尝试在Javascript中添加两个数字:

 var output;
 output = parseInt(a)+parseInt(b);
 alert(output);

它提供了错误的output值,例如如果a = 015b = 05。为什么会这样? 上述例子的预期结果应为20。

2 个答案:

答案 0 :(得分:7)

如果您使用0为数字添加前缀,则在基数8中指定它们。015因此为13,总和为18。

使用第二个parseInt参数强制基数:

var a = '015', b = '05';
var output;
output = parseInt(a, 10) + parseInt(b, 10);
alert(output); // alerts 20

答案 1 :(得分:0)

在许多编程语言中,以前导0开头的数字表示数字的基数8(八进制)表示。在这里你给八进制数作为输入并期望输出十进制,这就是你说输出错误的原因(这是正确的!wrt octal加法)

solution 1 : you can add two octal numbers and convert the result to decimal  

solution 2 : convert the octal numbers to decimal and then add them