问题
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