API
@-Formulas
JavaScript
LotusScript
Reg Exp
Web Design
Notes Client
XPages
 
Round to 0 or .5
In a recent project I had a need to round a number to the nearest half decimal (so the number would end in a .0 or a .5) using JavaScript. So, if the value was 100.1 or 100.2, it would return 100. If the value was 100.3 or 100.4, it would return 100.5, and so on. There's rounding functions built in to JavaScript, but this took a little different thinking to implement.

The function takes in a number with zero or one decimals. If there are zero decimals, the number is already a whole number. Using this assumption, the first thing the function does is get that decimal value. That is done in two statements. The first takes the number and subtracts the integer part. So we have only the decimal part. That decimal part is multiplied by 10 and then rounded to remove any fractional part that might remain. So, if the value coming in was 100.55, the decimal part would be 6. This was just an assurance, since I knew the numbers coming in had only one decimal place.

Once I had that decimal part, I checked to see if it was 5. If it was, then the number coming in was most likely "x.5" ("x" is the whole number part and the fractional part was ".5"). I say "most likely" because in my function I was receiving one decimal point. But if the number coming in was "x.49", the decimal part would result in 5 (4.9 gets rounded to 5). In this case, I want the function to properly return "x.5", so I take the integer part of the number, add 0.5 to it, and return that value.

Next, if the decimal part is less than 3 (0, 1, or 2) or greater than 7 (8 or 9), then the number is rounded (for values less than 3 it is rounded down to the next lower integer, and for values greater than 7 it is rounded up to the next higher integer) and the rounded number is returned.

The final check is when the decimal part is between 3 and 7 (3, 4, 5, 6, or 7). These values need to result in "x.5" (where x is the whole number part). So I take the integer part of the number and add 0.5 to it as the value to return. Here's the function:

function roundToHalf(value) {
   var converted = parseFloat(value); // Make sure we have a number
   var decimal = (converted - parseInt(converted, 10));
   decimal = Math.round(decimal * 10);
   if (decimal == 5) { return (parseInt(converted, 10)+0.5); }
   if ( (decimal < 3) || (decimal > 7) ) {
      return Math.round(converted);
   } else {
      return (parseInt(converted, 10)+0.5);
   }
}