Created
May 10, 2021 12:20
-
-
Save gabtoschi/4494d2be6ae2a079b6ae1880704d0828 to your computer and use it in GitHub Desktop.
Forma reduzida de números (3 mil, 42,3 mi, 321,9 bi) em português, feito em TypeScript
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 reducedFormStringsByDivisionAmount = [ | |
'', 'mil', 'mi', 'bi', 'tri', 'quatr', 'quint', 'sext', 'sept', | |
]; | |
export function getNumberReducedForm(value: number): string { | |
const numberStr = value.toString(); | |
// encontre a quantidade de classes numéricas que se tornarão não significativas | |
// 1350 = 1.350 => divisionAmount = 1 | |
// 18352140 = 18.352140 => divisionAmount = 2 | |
const divisionAmount = Math.trunc((numberStr.length - 1) / 3); | |
// encontre a forma numérica reduzida | |
// 1350 = 1.350 => numberRounded = '1,3' | |
// 18352140 = 18.352140 => numberRounded = '18,3' | |
const numberDivided = value / (Math.pow(1000, divisionAmount)); | |
let numberRounded = numberDivided.toFixed(1).replace('.', ','); | |
// caso o dígito depois da vírgula seja 0, descarte-o | |
const numberSplitted = numberRounded.split(','); | |
if (numberSplitted[1] === '0') { numberRounded = numberSplitted[0]; } | |
// retorne o número junto com a string de ordem de grandeza | |
return `${numberRounded} ${reducedFormStringsByDivisionAmount[divisionAmount]}`; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Muito bom!