本文介绍了为什么在2个检索到的值加起来之后不能执行toFixed()函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在进入JQuery脚本时,尝试对数字使用 toFix() JavaScript方法时遇到以下问题.

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

所以我有以下情况:

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

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

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

console.log()显示:

ANTICIPO CALCOLATO: 2192.002200.37

因此,这意味着JavaScript正确执行了添加操作.

So it means that JavaScript have correctly perform the addition.

问题是我们试图对这行进行取整以获得只有2个小数位的值:

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

anticipoCalcolato = anticipoCalcolato.toFixed(2);

在FireBug控制台中,我收到此错误消息:

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?

推荐答案

数学是错误的,因为您将两个字符串而不是两个数字加在一起.他的toFixed错误是因为您试图在字符串上使用toFixed,但是该方法仅存在于数字上.

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.

阅读.text()

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

这篇关于为什么在2个检索到的值加起来之后不能执行toFixed()函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 03:41