开发者

jQuery round decimal to .49 or .99

开发者 https://www.devze.com 2023-02-19 22:35 出处:网络
I\'m trying to work out how to round a decimal to .49 or .99. I have found the toFixed(2) function, but not sure how to round up or down.

I'm trying to work out how to round a decimal to .49 or .99.

I have found the toFixed(2) function, but not sure how to round up or down.

Basically need to get to the closest price point, so for example X.55 would go down to X.49 and X.84 would 开发者_开发百科go up to X.99.


This doesn’t require jQuery but can be done with plain JavaScript:

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

Note to also consider the case where the number would get rounded to 0 (price > 0.25) as that would yield -0.01 in this case.


If I had a dollar for every time jQuery made things more obtuse than they needed to be...

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;
};


I thing you cant round/fix to a specific number, you will need to check/caclulate the value, which could mean: rounding up then subtracting 1 or rounding up and subtracting 51.


This does not require jQuery. You just need Math class from javascript also rounding off will require some addtional subtraction since rounding will give nearest decimal


Editing aroth's answer a little bit in order to lets say we also need to round to nearest 5 multiply value

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;
};
0

精彩评论

暂无评论...
验证码 换一张
取 消