Skip to content

Instantly share code, notes, and snippets.

@bryanltobing
Created February 4, 2024 07:19
Show Gist options
  • Save bryanltobing/db586c9185d0fd4a19c929bba735dfd5 to your computer and use it in GitHub Desktop.
Save bryanltobing/db586c9185d0fd4a19c929bba735dfd5 to your computer and use it in GitHub Desktop.
Currency Formatter for TextInput
enum Currency {
IDR = "IDR",
USD = "USD",
}
const separator: Record<Currency, string> = {
IDR: ".",
USD: ",",
};
const extractNumbersFromString = (str: string) => str.replace(/\D/g, "");
const reverseString = (str: string) => {
const stringChars = str.split("");
let store: string[] = [];
stringChars.forEach((stringChar, index) => {
store[stringChars.length - 1 - index] = stringChar;
});
return store.join("");
};
const formatCurrency = (value: string, currency: Currency = Currency.IDR) => {
const selectedSeparator = separator[currency];
// 1. Get numbers extracted from string
const valueNumber = Number(extractNumbersFromString(value));
// 2. Remove 0
if (valueNumber === 0) {
return "";
}
// 3. Format Value
const stringValue = String(valueNumber);
// 4. Reverse stringValue
const reversedStringValue = reverseString(stringValue);
// 5. For every 3 chars add comma
const result: string[] = [];
for (let i = 0; i < reversedStringValue.length; i += 3) {
result.push(reversedStringValue.substring(i, i + 3));
}
return reverseString(result.join(selectedSeparator));
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment