Skip to content

Instantly share code, notes, and snippets.

@joepuzzo
Created September 8, 2021 18:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joepuzzo/b2fd03626e96817690b41f566568d866 to your computer and use it in GitHub Desktop.
Save joepuzzo/b2fd03626e96817690b41f566568d866 to your computer and use it in GitHub Desktop.
Round function based on precision
const MAP_NUM_TO_PRECISION = {
'-5': 'Hundred Thousandths',
'-4': 'Ten Thousandths',
'-3': 'Thousandths',
'-2': 'Hundredths',
'-1': 'Tenths',
'0': 'Ones',
'1': 'Tens',
'2': 'Hundreds',
'3': 'Thousands',
'4': 'Ten Thousands',
'5': 'Hundred Thousands',
};
const round = ( n, precision, type = 'IT' ) => {
const place = Math.pow(10, precision)
let result = 0;
if( type === 'UP' ){
result = Math.ceil( n / place) * place;
}
else if( type === 'DOWN' ){
result = Math.floor( n / place) * place;
} else {
result = Math.round( n / place) * place;
}
console.log( 'Round:', n, type , 'to', MAP_NUM_TO_PRECISION[precision], 'place.. result', result);
}
const num = 5134.050016
round(num, 0);
round(num, 0, 'UP');
round(num, 0, 'DOWN');
console.log('\n');
round(num, 1);
round(num, 1, 'UP');
round(num, 1, 'DOWN');
console.log('\n');
round(num, 2);
round(num, 2, 'UP');
round(num, 2, 'DOWN');
console.log('\n');
round(num, -1);
round(num, -1, 'UP');
round(num, -1, 'DOWN');
console.log('\n');
round(num, -2);
round(num, -2, 'UP');
round(num, -2, 'DOWN');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment