Convert value to number returns NaN

2

I'm reading a book about JavaScript, but in a certain part the code in the book does not work.

The part is:

var qtyElements = produto[i].getElementsByClassName("quantity");
var qtyText = qtyElements[0].value;
var quantity = moneyTextToFloat(qtyText);
console.log(quantity);

It was to return the quantity of a class, however in the console I get NaN .

Complete code:

function moneyTextToFloat(text){
  var clean = text.replace("R$","").replace(",",".");
  return parseFloat(clean);
}

function floatToMoney(value){
  var text = (value < 1 ? "0" : 0 ) + Math.floor(value * 100);
  text = "R$" + text;
  return text.substr(0, text.length -2) + "," + text.substr(-2);
}
function readTotal(){
  var total = document.getElementById("total");
  return moneyTextToFloat(total.innerHTML);
}
function writeTotal(value){
  var total = document.getElementById("total");
  total.innerHTML = floatToMoney(value);
}
var totalProdutos = 0;
var produto = document.getElementsByClassName("produto");
for (let i = 0; i < produto.length; i++){
  var priceElements = produto[i].getElementsByClassName("price");
  var priceText = priceElements[0].innerHTML;
  var price = moneyTextToFloat(priceText);


  var qtyElements = produto[i].getElementsByClassName("quantity");
  var qtyText = qtyElements[0].value;
  var quantity = moneyTextToFloat(qtyText);
  console.log(quantity);

}
<html>
<head>
  <title>BIBLIOTECA</title>
  <meta charset="utf-8">

</head>
<body>
    <table>
      <tbody>	
        <tr class="produto">
          <td class="td"><div class="price">R$29,90</div></td>
          <td><input type="number" class="quantity"></td>
        </tr>
        <tr class="produto">
          <td><div class="price">R$59,90</div></td>
          <td> <input type="number" class="quantity">
          </td>
        </tr>
        <tr class="produto">
          <td><div class="price">R$99,90</div></td>
          <td><input type="number" class="quantity"></td>
        </tr>
      </tbody>

      <tr>
        <td></td>
        <td>Total de compras</td>
        <td><div id="total">R$ 189,90</div></td>
        <td></td>
      </tr>
    </table>

<script type="text/javascript" src="JS/carrinhoDeCompra.js"></script>
</body>
</html>
    
asked by anonymous 14.12.2018 / 16:20

1 answer

3

It is returning. In this case, parseFloat ("") out parseFloat (null) returns NaN because there is no number. NaN means Not a Number. So if you want the result to be zero when there is no number inside your field you can:

1 - Force zero if the result is NaN:

return parseFloat(clean) || 0;

2 - Make the default value of the input be 0:

<input type="number" class="quantity" value="0">
    
14.12.2018 / 17:37