Skip to content

Instantly share code, notes, and snippets.

@gabtoschi
Created May 10, 2021 12:20
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gabtoschi/4494d2be6ae2a079b6ae1880704d0828 to your computer and use it in GitHub Desktop.
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
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]}`;
}
@theuves
Copy link

theuves commented Mar 5, 2022

Muito bom!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment