Javascript function with NaN error

2

This function is returning error: NaN, to convert back to text.

function floatToMoneyText(value) {
            var text = (value < 1 ? "0" : " ") + Math.floor(value * 100);
            text = "R$ " + text;
            return text.substr(0, text.length - 2) + "," + text.substr(-2); 
        }

Here is the link: link

    
asked by anonymous 08.06.2016 / 04:03

1 answer

1

Watch out for these books, especially those with bad examples. The function itself had no problem, except that it tried to execute something with an invalid argument. The problem was in the past, changing to send a numeric value ends up working. It's a shame that a book encourages even use of monetary value with float in an exercise. Whoever is learning thinks this is right. It is obvious that the book should teach other things wrong. The very logic of converting these functions is bad.

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

function floatToMoneyText(value) {
  var text = (value < 1 ? "0" : " ") + Math.floor(value * 100);
  return "R$ " + text.substr(0, text.length - 2) + "," + text.substr(-2); 
}

var total = document.getElementById("total");
var mostrar = moneyTextToFloat(total.innerHTML);
alert(mostrar);
var mostrarTexto = floatToMoneyText(29.90);
alert(mostrarTexto);
<body>

  <table>
    <tbody>
      <tr>
        <td>
          <div>R$ 29,90</div>
        </td>
        <td>
          <input type="number">
        </td>
      </tr>
    </tbody>
    <tr>
      <td> </td>
      <td>Total da compra</td>
      <td><div id="total">R$ 29,90</div></td>
      <td> </td>
    </tr>
  </table>
    
08.06.2016 / 04:24