Javascript function with Nan error

Asked

Viewed 254 times

2

This function is returning error: Nan, to convert again 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: https://jsfiddle.net/nkf3tLkq/

  • What is the purpose of this function? It does not seem to do anything useful.

  • There’s in the book I’m reading, I didn’t get it right.

  • Seems like a pretty bad book to me.

  • is to demonstrate the use of functions, floor, substr.

1 answer

3


Be careful with these books, especially if they have bad examples. The function itself had no problem, except for the fact of trying to execute something with an invalid argument. The problem was in the past, changing to send a numerical value ends up working. It is a pity that a book encourages, even in an exercise, the use of monetary value with float. Those who are learning think this is right. It is obvious that the book must teach other wrong things. 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>

I put in the Github for future reference.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.