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.
What is the purpose of this function? It does not seem to do anything useful.
– Maniero
There’s in the book I’m reading, I didn’t get it right.
– user48410
Seems like a pretty bad book to me.
– Maniero
is to demonstrate the use of functions, floor, substr.
– user48410