【问题标题】:jQuery round decimal to .49 or .99jQuery 将小数点四舍五入为 .49 或 .99
【发布时间】:2011-07-22 19:59:12
【问题描述】:

我正在研究如何将小数四舍五入为 .49 或 .99。

我找到了toFixed(2) 函数,但不知道如何向上或向下舍入。

基本上需要达到最接近的价格点,例如 X.55 会下降到 X.49,X.84 会上升到 X.99。

【问题讨论】:

标签: jquery math floating-point rounding decimal


【解决方案1】:

这不需要 jQuery,但可以使用纯 JavaScript 完成:

Math.round(price*2)/2 - 0.01

请注意,还要考虑将数字四舍五入为 0 (price > 0.25) 的情况,因为在这种情况下会产生 -0.01。

【讨论】:

  • 这是一种享受。好东西!正如你所指出的,我会确保考虑 -0.01 的可能性。
【解决方案2】:

如果每次 jQuery 让事情变得比他们需要的更迟钝时我都有一美元......

window.round = function(num) {
    cents = (num * 100) % 100;
    if (cents >= 25 && cents < 75) {
        //round x.25 to x.74 -> x.49
        return Math.floor(num) + 0.49;
    }
    if (cents < 25) {
        //round x.00 to x.24 -> [x - 1].99
        return Math.floor(num) - 0.01;
    }
    //round x.75 to x.99 -> x.99
    return Math.floor(num) + 0.99;
};

【讨论】:

    【解决方案3】:

    我认为您无法四舍五入/修复到特定数字,您需要检查/计算该值,这可能意味着:四舍五入然后减去 1 或四舍五入并减去 51。

    【讨论】:

      【解决方案4】:

      这不需要 jQuery。你只需要 JavaScript 中的数学类,四舍五入也需要一些额外的减法,因为四舍五入会给出最接近的小数

      【讨论】:

        【解决方案5】:

        稍微编辑 aroth 的答案,让我们说我们还需要四舍五入到最接近的 5 乘数值

        window.round = function(num) {
        cents = (num * 100) % 100;
        if (cents >= 25 && cents < 75) {
            //round x.25 to x.74 -> x.49
            return Math.ceil(num/5)*5  + 0.49;
        }
        if (cents < 25) {
            //round x.00 to x.24 -> [x - 1].99
            return Math.ceil(num/5)*5  - 0.01;
        }
        //round x.75 to x.99 -> x.99
        return Math.ceil(num/5)*5  + 0.99;
        };
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多