Why I can't perform the toFixed() function after the sum of 2 retrieved values?

Deadly 提交于 2019-12-12 05:25:02

问题


Into a JQuery script I have the following problem trying to use the toFix() JavaScript method on a number.

So I have the following situation:

var anticipoProgetto = $("#valoreAnticipo").text();
var saldoProgetto = $("#valoreSaldo").text();

var anticipoCalcolato = (saldoProgetto + anticipoProgetto);
console.log("ANTICIPO CALCOLATO: " + anticipoCalcolato);
anticipoCalcolato = anticipoCalcolato.toFixed(2);

$("#anticipoModaleUlterioreSaldo").val(anticipoCalcolato);

The console.log() show:

ANTICIPO CALCOLATO: 2192.002200.37

So it means that JavaScript have correctly perform the addition.

The problem is that wehn try to perorm this line to obtain a value with only 2 decimals digits:

anticipoCalcolato = anticipoCalcolato.toFixed(2);

in the FireBug console I obtain this messagge error:

TypeError: anticipoCalcolato.toFixed is not a function
    anticipoCalcolato = anticipoCalcolato.toFixed(2);

Why? What am I missing? How can I fix this issue?


回答1:


The math is wrong because you are adding two string together, not two numbers. And he toFixed error is because you are trying to use toFixed on a string, but that ethod only exists on numbers.

Convert the strings to numbers when you read the .text()

var anticipoProgetto = parseFloat($("#valoreAnticipo").text()),
    saldoProgetto = parseFloat($("#valoreSaldo").text()),
    anticipoCalcolato = anticipoProgetto + saldoProgetto,
    fixed = anticipoCalcolato.toFixed(2);



回答2:


@espacarello is correct, you need to cast from string to number. It may be more to your intent to cast them as you read them.

If #valoreAnticipo is an input element, consider switching to .val() instead of .text()

var anticipoProgetto = parseFloat($("#valoreAnticipo").text()) || 0;
var saldoProgetto = parseFloat($("#valoreSaldo").text()) || 0;

var anticipoCalcolato = (saldoProgetto + anticipoProgetto);
console.log("ANTICIPO CALCOLATO: " + anticipoCalcolato);
anticipoCalcolato = anticipoCalcolato.toFixed(2);

$("#anticipoModaleUlterioreSaldo").val(anticipoCalcolato);


来源:https://stackoverflow.com/questions/34995346/why-i-cant-perform-the-tofixed-function-after-the-sum-of-2-retrieved-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!