Search code examples
javascripthtmlparseint

dinner cost calculator trouble converting string to integer


I'm using parseInt to convert .values from strings to numbers. However, if the user inputs a decimal value the output is NaN. Here is my code:

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;
}

What am I doing wrong? Is there a more rational way to convert these default strings into numbers instead of parseInt?

Thanks!


Solution

  • Use parseFloat() instead of parseInt() Usage: taxRate = parseFloat(taxRate);

    As a better programming practice you should avoid exceptions in such conversions.One easy way to do robust type-checking in this Javascript scenario is to avoid:

    • undeclared variables
    • undeclared properties on Javascript objects (aka dictionary)
    • Lnull values
    • NaN values

    Here is a simple and quick overview:

    //
    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
    

    Other than that please refer this link and see how you avoid exceptions in such conversions.