Win a copy of The Way of the Web Tester: A Beginner's Guide to Automating Tests this week in the Testing forum!

# Round number to nearest quarter

Lauren Pender
Greenhorn
Posts: 5
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
I forgot to say that this is in javascript.

Chris Treglio
Ranch Hand
Posts: 64
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.