Created
September 8, 2021 18:53
-
-
Save joepuzzo/b2fd03626e96817690b41f566568d866 to your computer and use it in GitHub Desktop.
Round function based on precision
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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