Mario Cordeiro Mario Cordeiro - 6 months ago 15
Javascript Question

javascript toFixed(2) not working

I have this piece of code:

var desconto = document.getElementById('desconto').value;
var portes = document.getElementById('portes').value;
var pr_equipamentos = document.getElementById('pr_total_equipamentos_escondido').value;
var pr_total;

pr_total = (pr_equipamentos * ((100-desconto)/100)) + portes;
pr_total = pr_total.toFixed(2);
alert(pr_total);

document.getElementById('pr_total_proposta').innerHTML = pr_total + " €";


The ID's
desconto
,
portes
and
pr_total_equipamentos_escondido
are input type in a form.

In this case I'm not able to use the
toFixed(2)
. The first formula of pr_total gives me the number:
1324.7865372846
and the next step is not working
(pr_total = pr_total.toFixed(2))
.

What am I doing wrong?

Answer

When you define a var, in JavaScript it is a string, so you need to parse.

try:

pr_total = parseFloat(pr_total).toFixed(2);
Comments