晚餐成本计算器无法将字符串转换为整数

dinner cost calculator trouble converting string to integer

我正在使用 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?

谢谢!

您可以直接使用 Number 构造函数,而无需将其实例化为 return 文字数字。或者你可以使用 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;
}
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>

使用 parseFloat() 而不是 parseInt() 用法:taxRate = parseFloat(taxRate);

作为一种更好的编程习惯,您应该在这种情况下避免异常 conversions.One 在此 Javascript 场景中进行稳健类型检查的简单方法是避免:

  • 未声明的变量
  • Javascript 对象(又名字典)的未声明属性
  • L 个空值
  • NaN 值

这里有一个简单快速的概述:

//
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 link 并了解如何避免此类转换中的异常。