javascript - 为什么 "toFixed"会阻止我的函数多次运行?

标签 javascript tofixed

我正在尝试制作一个点钞机,您每次点击它,您的“钱”数额就会增加 1 美元。但是,我希望钱的显示始终显示 2 个小数位。当我使用 toFixed(2) 修复此问题时,它使得该函数只能运行一次,并且在刷新页面之前不会再次运行。

我已经尝试删除代码的 toFixed 部分,它可以正常运行,但它不会像我希望的那样显示小数位。

let money = 0;
let mpc = 1;
let moneySuffix = "";

function coinClick() {
    money = money + mpc;
    money = money.toFixed(2);

    if (money >= 1000) {
        moneySuffix = " thousand";
    } else if (money >= 1000000) {
        moneySuffix = " million";
    } else if (money >= 1000000000) {
        moneySuffix = " billion";
    } else if (money >= 1000000000000) {
        moneySuffix = " trillion";
    } else if (money >= 1000000000000000) {
        moneySuffix = " quadrillion";
    } else {
        moneySuffix = "";
    }

    document.querySelector("#totalMoney").innerHTML = "$" + money + moneySuffix;
}

本以为点击一次显示1.00,点击两次显示2.00,等等,结果点击一次显示1.00,然后就不能再增加了。

最佳答案

方法Number.toFixed()返回一个字符串,因此您正在将初始数字类型转换为字符串,这可能会导致后续 clicks 出错,因为您将尝试在字符串。如果您尝试向用户显示带两位小数的数字,则仅将此方法应用于将向用户显示的代码部分:

let money = 0;
let mpc = 1;
let moneySuffix = "";

function coinClick()
{
    money = money + mpc;

    if (money >= 1000 && money < 1000000) {
        moneySuffix = " thousand";
    } else if (money >= 1000000 && money < 1000000000) {
        moneySuffix = " million";
    } else if (money >= 1000000000 && money < 1000000000000) {
        moneySuffix = " billion";
    } else if (money >= 1000000000000 && money < 1000000000000000) {
        moneySuffix = " trillion";
    } else if (money >= 1000000000000000) {
        moneySuffix = " quadrillion";
    } else {
        moneySuffix = "";
    }

    // Note, we use toFixed() just here, but we don't change the numeric type
    // of the variable money.
    document.querySelector("#totalMoney").innerHTML = "$" + money.toFixed(2) + moneySuffix;
}

请注意,我还对 if-else block 进行了更改以使其正常工作,并且作为旁注,请注意存在限制:Number.MAX_SAFE_INTEGER

关于javascript - 为什么 "toFixed"会阻止我的函数多次运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55604379/

相关文章:

javascript - jQuery .css() 附加或覆盖

javascript - Canvas 未合并并导致仅显示背景图像

javascript - 使用 jQuery 验证用户名

javascript - 为什么 (-2.4492935982947064e-16).toFixed(5) 等于 "-0.00000"?

javascript - 使用reduce方法JS后修复

javascript - 使用meteor 和 Aldeed 的 autoform 进行动态形式概括和删除

javascript - 从网页自动安装apk文件

php - php 中的 number_format() 与 jQuery 中的 toFixed() 进行验证

javascript - 来自输入的 parseInt 值,并使用 Javascript 检查最后一个值的总和

javascript - 从小数点后第三位开始不四舍五入