-1
我有我不确定如何解释的情况: 什么错误我是,我打开代码,我写了一些值(例如: 你有多少费用:100 您的服务如何:10 有多少人共享:2)之前,我点击计算我打开控制台。如果我写:.value返回字符串,直到我将它保存到变量
>bill.value
<"100"
我得到一个字符串,如预期的那样。但后来我点击计算,我得到的是:
100
5
为什么100?为什么它突然返回字符串的数字?
我该怎么在最后做数学呢?只有我变成数字的是Number(bill.value)。服务和人员应该仍然是字符串?
var button = document.querySelector("button");
var tip = document.getElementById("tip");
var total;
button.addEventListener("click", function() {
var bill = document.querySelector("input");
console.log(bill.value)
var people = document.getElementById("people").value;
var service = document.getElementsByTagName("select")[0].value;
total = (service * Number(bill.value))/people
tip.textContent = total;
console.log(total)
});
<h1>Tip Calculator</h1>
<div>How much was your bill?</div>
<label for="bill">$</label>
<input type="number" id="bill">
<div>How was your service?</div>
<select>
<option disabled selected value="0">Choose</option>
<option value="0.30">30% - Outstanding</option>
<option value="0.20">20% - Good</option>
<option value="0.15">15% - It was okaya</option>
<option value="0.10">10% - Bad</option>
<option value="0.05">5% - Terible</option>
</select>
<div>How many people are sharing the bill?</div>
<label>
<input type="number" id="people">people</label>
<button>Calculate!</button>
<span id="tip"></span>
我该怎么在最后做数学呢。只有我变成数字的是Number(bill.value)。服务和人员应该仍然是字符串? –
伊戈尔,看看我附加到答案的小提琴,你会注意到我在任何算术之前将两个bill.value和服务转换为一个浮点数。 – sheeldotme
嗨sheeldotme。非常感谢您的帮助。 parseFloat看起来像是一个完美的解决方案,但请帮我解释一下,也许我没有得到它。我感兴趣的是我的例子如何运作?我可以在没有parseFloat的情况下进行算术运算,或者将人员和服务转换为Number()。他们仍然是字符串,但数学作品。我错过了什么? 是的,我知道1,我没有完成它,直到我第一次向自己解释。 –