Skip to content

Instantly share code, notes, and snippets.

@caneruguz
Last active August 29, 2015 14:16
Show Gist options
  • Save caneruguz/0fd1cf8220d502a51800 to your computer and use it in GitHub Desktop.
Save caneruguz/0fd1cf8220d502a51800 to your computer and use it in GitHub Desktop.
Rounding multiple times while not losing remainders in Javascript
/*
* Return the rounded number and the new remainder using past remainder.
*
* @param {number} number The number that needs to be rounded
* @param {number} priorRemainder The remainder that is left over from last time that needs to be added to the calculation
*/
function multiRound(number, priorRemainder) {
var floored = Math.floor(number + priorRemainder);
var difference = (number + priorRemainder) - floored;
return {
number : floored,
remainder : difference
};
}
/*
* Demonstrate rounding of an array
*
* @param {Array} arr A list of numbers to be rounded
* @returns {Array} New array with adjusted numbers
*/
function roundArray(arr) {
var globalRemainder = 0;
return arr.map(function(item){
var result = multiRound(item, globalRemainder);
globalRemainder = result.remainder;
return result.number
});
}
/* Now try it */
var arr = [1.1, 2.2, 3.3, 4.4, 5.5, 6.6];
var newArr = roundArray(arr);
/* Result should be [1, 2, 3, 5, 5, 7] */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment