Skip to content

Instantly share code, notes, and snippets.

@nnnnnoel
Created June 2, 2020 02:38
Show Gist options
  • Save nnnnnoel/8f796ff76d5d2abe769351b056620bce to your computer and use it in GitHub Desktop.
Save nnnnnoel/8f796ff76d5d2abe769351b056620bce to your computer and use it in GitHub Desktop.
React Native toCommaNumber
export function removeDot(str: string): string {
return str.replace(/(^0)(?=[^.])/, '');
}
export function replComma(str: string): string {
return removeDot(str.replace(/(^[\d,]+\.(?:\d*[^0])?)(0*)$/, '$1').replace(/\.$/, ''));
}
export function addComma(str: string): string {
return str.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}
export function toCommaNumber(number: number | string, input?: boolean): string {
if (!number) {
return '0';
}
const numbers = number.toString().split('.');
numbers[0] = addComma(numbers[0]);
if (input) {
if (typeof numbers[1] === 'string') return removeDot([numbers[0], numbers[1]].join('.'));
return removeDot(numbers[0]);
}
if (typeof number === 'number') {
if (Platform.OS === 'ios') {
return number.toLocaleString();
}
if (typeof numbers[1] === 'string') return replComma([numbers[0], numbers[1]].join('.'));
return replComma(numbers[0]);
}
if (typeof numbers[1] === 'string') return replComma([numbers[0], numbers[1]].join('.'));
return replComma(numbers[0]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment