当我通过此代码输入我的数字时,我希望能够得到一个小数点,而代码所做的就是当你输入数字时它只是显示数字,就像我点击5次将是55但是如果我想要5.5,我该怎么做?
var number = '';
var number1 = '';
var number2 = '';
function selectNum(num)
{
number += num;
number = parseInt(number);
document.getElementById("outputbox").innerHTML = number;
}
<button onclick = "selectNum('7')">7</button>
<button onclick = "selectNum('8')">8</button>
<button onclick = "selectNum('9')">9</button>
<button onclick = "selectNum('4')">4</button>
<button onclick = "selectNum('5')">5</button>
<button onclick = "selectNum('6')">6</button>
<button onclick = "selectNum('1')">1</button>
<button onclick = "selectNum('2')">2</button>
<button onclick = "selectNum('3')">3</button>
<button onclick = "selectNum('0')">0</button>
<button onclick = "selectNum('.')">.</button>
答案 0 :(得分:0)
问题是你在有机会显示字符串之前调用parseFloat
。根据{{1}}的规则,参数parseFloat
被解析为1.
,并且小数位被删除。
要解决这个问题,我会尝试这样的事情:
1
var number = '';
var number1 = '';
var number2 = '';
function selectNum(num)
{
number += num;
document.getElementById("outputbox").innerHTML = number;
if (!number.slice(-1) == '.') {
number = parseFloat(number);
}
}
现在唯一的问题是字符串中允许多个小数。