1
I have the following function that brings a string as number in javascript. It can bring float value as 10.00 and int as 12. Why is it wrong? Gives as replace is Undefined on the line: text.replace("R$","");
function moneyTextToFloat(text){
var cleanText = text.replace("R$","");
cleanText = cleanText.replace(",",".");
return parseFloat(cleanText);
}
Here is the javascript code, which was not mentioned above:
// faz o cálculo do total junto com o preço da taxa de entrega
function calculateTotalProductsEntrega()
{
var produtos = document.getElementsByClassName("produto");
var totalProdutos = 0;
for(var pos = 0; pos < produtos.length; pos++)
{
// seleciona o preço
var priceElements = produtos[pos].getElementsByClassName("precoproduto");
var priceText = priceElements[0].innerHTML;
var price = moneyTextToFloat(priceText);
// seleciona a quantidade
var qtyElements = produtos[pos].getElementsByClassName("quantidadeproduto");
var qtyText = qtyElements[0].value;
var quantity = moneyTextToFloat(qtyText);
// pega a taxa de entrega prevista
var shiptElements = produtos[pos].getElementsByClassName("taxaentrega");
var shiptText = shiptElements[0].innerHTML;
var shipt = moneyTextToFloat(shiptText);
var subtotal = (quantity * price) + shipt;
totalProdutos += subtotal;
}
return totalProdutos;
}
What are you calling that function? And that line
text.replace("R$","");
is so alone without being used?– Sergio
Not the top line talks about the error itself
– Felipe Michael da Fonseca
What are you calling that function?
– Sergio
Well I’ll put in the answer the javascript
– Felipe Michael da Fonseca
You can ask the question that we help to format. Click on [Edit].
– Sergio
If the variable
text
has not the methodreplace
is because it is not a string. Review what you pass to the function.– Oralista de Sistemas
As already mentioned by @Renan if this happens it is because "text" is not string. Make text.toString(). replace("R$", "")
– GeekSilva
From what I see
moneyTextToFloat
will always receive a string. You can make an example here or in a jsFiddle that plays the problem online?– Sergio