Skip to content

Instantly share code, notes, and snippets.

@akbarjondev
Last active November 2, 2022 03:00
Show Gist options
  • Save akbarjondev/288376789868ef9ef5b3eb5a26939b95 to your computer and use it in GitHub Desktop.
Save akbarjondev/288376789868ef9ef5b3eb5a26939b95 to your computer and use it in GitHub Desktop.
Separate thousands, used for prices
const priceUtility = (pr: string | number): string => {
// remove spaces
const price: string = pr.toString().replaceAll(' ', '');
// get hole part
const holePart: number = parseInt(price);
// get float part of price if exist
const floatPart: string =
parseFloat(price) - holePart === 0
? ''
: (parseFloat(price) - holePart).toFixed(2).substring(1);
let result = '';
let counter = 0;
let stringPrice: string = holePart.toString();
for (let i = stringPrice.length - 1; i >= 0; i--) {
if (counter === 3) {
// add space in front of thousand
result = ' ' + result;
counter = 0;
}
counter++;
result = stringPrice[i] + result;
}
return result + floatPart;
};
priceUtility('55990.99'); // '55 990.99'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment