我正在使用parseInt将.values从字符串转换为数字。但是,如果用户输入十进制值,则输出为NaN。这是我的代码:
Dinner Cost:<input type="text" id="cost" /><br /><br />
Tax Rate:<input type="text" id="taxRate" /><br /><br />
<button id="btn">Determine Total Costs</button><br /><br />
<p id="para"></p>
document.getElementById("btn").addEventListener('click', totalCosts);
function totalCosts() {
var dinnerCosts = document.getElementById("cost").value;
var taxRate = document.getElementById("taxRate").value;
taxRate = parseInt(taxRate);
dinnerCosts = parseInt(dinnerCosts);
var taxCost = dinnerCosts * taxRate;
var totalCost = dinnerCosts + taxCost;
return document.getElementById("para").innerHTML = "Your dinner cost " + dinnerCosts + ", your tax costs " + taxCost + ", for a total cost of " + totalCost;
}
我做错了什么?有没有更合理的方法将这些默认字符串转换为数字而不是parseInt?
谢谢!
答案 0 :(得分:2)
使用parseFloat()而不是parseInt()用法:taxRate = parseFloat(taxRate);
作为一种更好的编程实践,你应该避免在这种转换中出现异常。在这个Javascript场景中进行健壮的类型检查的一种简单方法是避免:
以下是一个简单快速的概述:
//
var vfftest = 0.05; // float
var viitest = 3000; // integer
var vssblank = ''; // empty string
var vssnonblank = 'hello'; // non-empty string
var vddempty = {}; // dictionary with no name-value pairs
var vddnonempty = {'alpha':1,'bravo':'two'}; // dictionary with name- value pairs
var vnull = null; // null
// check parseFloat
console.log( parseFloat(vssnonblank) ); // NaN
console.log( parseFloat(vssblank) ); // NaN
console.log( parseFloat(vfftest) ); // 0.05
console.log( parseFloat(viitest) ); // 3000
console.log( parseFloat(vnull) ); // NaN
console.log( parseFloat(vddempty) ); // NaN
console.log( parseFloat(vddnonempty) ); // NaN
console.log( parseFloat(vnoExisto) ); // EXCEPTION
除此之外,请参阅this链接,了解如何避免此类转换中的例外情况。
答案 1 :(得分:1)
您可以直接使用Number
构造函数,而无需实例化它以返回文字编号。或者,您可以使用parseFloat
document.getElementById("btn").addEventListener('click', totalCosts);
function totalCosts() {
var dinnerCosts = document.getElementById("cost").value;
var taxRate = document.getElementById("taxRate").value;
taxRate = Number(taxRate);
dinnerCosts = Number(dinnerCosts);
var taxCost = dinnerCosts * taxRate;
var totalCost = dinnerCosts + taxCost;
return document.getElementById("para").innerHTML = "Your dinner cost " + dinnerCosts + ", your tax costs " + taxCost + ", for a total cost of " + totalCost;
}
&#13;
Dinner Cost:<input type="text" id="cost" /><br /><br />
Tax Rate:<input type="text" id="taxRate" /><br /><br />
<button id="btn">Determine Total Costs</button><br /><br />
<p id="para"></p>
&#13;