2

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.

mskfisher
  • 3,291
  • 4
  • 35
  • 48
diggersworld
  • 12,770
  • 24
  • 84
  • 119
  • read [similar concept](http://stackoverflow.com/questions/477892/in-jquery-whats-the-best-way-of-formatting-a-number-to-2-decimal-places) – xkeshav Mar 25 '11 at 10:56

5 Answers5

11

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.

Gumbo
  • 643,351
  • 109
  • 780
  • 844
1

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;
};
aroth
  • 54,026
  • 20
  • 135
  • 176
0

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.

Mark Redman
  • 24,079
  • 20
  • 92
  • 147
0

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

sushil bharwani
  • 29,685
  • 30
  • 94
  • 128
0

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;
};
mepsd
  • 21
  • 1
  • 2