Created
June 2, 2020 02:38
-
-
Save nnnnnoel/8f796ff76d5d2abe769351b056620bce to your computer and use it in GitHub Desktop.
React Native toCommaNumber
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
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