• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Round number to nearest quarter

 
Lauren Pender
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a bunch of fields and I would like to round them to the nearest .25. So if you enter 1.04 it rounds it to 1.0. If you have 1.23, it rounds it to 1.25. 1.65 to 1.75.
Thank you
 
Lauren Pender
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I forgot to say that this is in javascript.
 
Chris Treglio
Ranch Hand
Posts: 64
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can do this with the modulo (%) operator, like this
function round(value, increment) {
// value will be the number we'll round
// increment will be the 'round to' - in your case, .25
var remain;
var roundvalue;
var result;
remain = value % increment; // this will be somewhere between 0 and .25
roundvalue = increment / 2;

if (remain >= roundvalue){ // rounding up
result = value - remain;
result += increment;
}
else { // rounding down
result = value - remain;
}
return result;
}
I think that will do it. I didn't really run this through the paces with all the browsers, but I think that's it.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic