Skip to content

Instantly share code, notes, and snippets.

@wilsaantos
Last active December 17, 2024 21:06
Show Gist options
  • Save wilsaantos/d38880b6fc919352719f19442de5acdf to your computer and use it in GitHub Desktop.
Save wilsaantos/d38880b6fc919352719f19442de5acdf to your computer and use it in GitHub Desktop.
INPUT_CURRENCY_BRL.ts
*/ HTML ATTRIBUTES
matInput
type="text"
[value]="
formGroup.get('')?.value
| currency : 'BRL' : 'symbol' : '1.2-2' : 'pt-BR'
"
(input)="inputChange($event)"
*/
inputChange(event: any) {
const input = event.target as HTMLInputElement;
const cursorPosition = input.selectionStart;
let [integerPart, decimalPart = ''] = input.value.split(',');
const qtdAposVirgula = decimalPart.length;
// Verifica se o cursor está na posição final
if (cursorPosition === input.value.length && !Number.isNaN(parseInt(event.data))) {
// Quando há mais de 2 casas decimais, adiciona o caractere à parte inteira
if (qtdAposVirgula > 2) {
const penultimoCaractere = decimalPart.slice(-3, -2);
if (parseInt(penultimoCaractere) !== 0) {
decimalPart = decimalPart.slice(0, 1).concat(event.data);
} else {
integerPart = integerPart.concat(event.data);
input.value = [integerPart, decimalPart].join(',');
}
}
}
// Limita a quantidade de casas decimais a 2
if (qtdAposVirgula > 2) {
decimalPart = decimalPart.slice(0, 2);
input.value = [integerPart, decimalPart].join(',');
}
// Remove caracteres não numéricos e converte a string para float
const numericValue = input.value.replace(/[^\d,]/g, '').replace(',', '.');
this.formGroup.get('')?.setValue(parseFloat(numericValue));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment