最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript toFixed(2) not working - Stack Overflow

programmeradmin3浏览0评论

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?

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?

Share Improve this question edited Nov 21, 2013 at 11:01 Zaheer Ahmed 28.6k12 gold badges76 silver badges112 bronze badges asked Nov 21, 2013 at 10:52 Mario CordeiroMario Cordeiro 1254 silver badges16 bronze badges 4
  • 4 Please describe the "not working" part. What happens, and what was supposed to happen. – undefined Commented Nov 21, 2013 at 10:54
  • Can you provide a jsfiddle or some other executable version of the problem? – Juho Vepsäläinen Commented Nov 21, 2013 at 10:56
  • In this case, the "alert(pr_total)" doesn´t give me the message. If I delete the line "pr_total = pr_total.toFixed(2)" the alert is working, so I suppose the line "pr_total = pr_total.toFixed(2)" has some error. My intention is to have the following alert message: "1324.78". – Mario Cordeiro Commented Nov 21, 2013 at 10:59
  • 2 If you've bothered to take a look at the console, you would have seen an error message: TypeError: pr_total.toFixed is not a function. This happens since values of inputs are strings. Convert them to numbers before maths... – Teemu Commented Nov 21, 2013 at 11:02
Add a ment  | 

2 Answers 2

Reset to default 7

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

try:

pr_total = parseFloat(pr_total).toFixed(2);
_txt3.value = (parseFloat(t1) - parseFloat(t2));


_txt3.value = parseFloat(_txt3.value).toFixed(2);
发布评论

评论列表(0)

  1. 暂无评论