Skip to content

Instantly share code, notes, and snippets.

@KerryJones
Last active January 2, 2016 00:29
Show Gist options
  • Select an option

  • Save KerryJones/8223805 to your computer and use it in GitHub Desktop.

Select an option

Save KerryJones/8223805 to your computer and use it in GitHub Desktop.
Javascript function that rounds up to a specific ending, such as "9.99" or "8.88" from any number or any ending.
/**
* Does the "Math.ceil" but goes to a given ending, such as "9.99" or "8.88".
*
* Example: Math.ceilEnding( 37.46, 9.99 ) returns 39.99
*
* @param float number
* @param float ending
* @return float
*/
Math.ceilEnding = function( number, ending ) {
var numberEnding = number.toFixed( 2 ).substr( -parseFloat( ending ).toFixed(2).length ), difference = numberEnding - ending, placeValue = Math.pow( 10, Math.floor( ending ).toString().length );
if ( difference > 0 ) {
return Math.round( ( number + placeValue - difference ) * 100 ) / 100;
} else if ( difference < 0 ) {
return Math.round( ( number - difference ) * 100 ) / 100;
}
return number;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment