为什么在 2 个检索到的值相加后我无法执行 toFixed() 函数? [英] Why I can't perform the toFixed() function after the sum of 2 retrieved values?

查看:23
本文介绍了为什么在 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() 函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆