Created
February 4, 2024 07:19
-
-
Save bryanltobing/db586c9185d0fd4a19c929bba735dfd5 to your computer and use it in GitHub Desktop.
Currency Formatter for TextInput
This file contains 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
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