问题
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.
回答1:
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.
回答2:
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;
};
回答3:
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.
回答4:
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
来源:https://stackoverflow.com/questions/5431440/jquery-round-decimal-to-49-or-99