-
Notifications
You must be signed in to change notification settings - Fork 113
/
add.ts
26 lines (21 loc) · 819 Bytes
/
add.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import { digitsFaToEn } from "../digits";
import { isPersian } from "../isPersian";
/**
* Add Commas to numbers
*
* @method addCommas
* @param {number} number, eg: 300000
* @return {string} string of separated numbers by commas, eg: 30,000
*/
const addCommas = (number: number | string): string => {
if (typeof number !== "number" && typeof number !== "string") return "";
const convertedToString = number.toString();
const tokenizedToEnglish = isPersian(convertedToString)
? (digitsFaToEn(convertedToString) as string)
: convertedToString;
const tokenizedNumber = tokenizedToEnglish.split(".");
const integer = tokenizedNumber[0].replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,");
const decimal = tokenizedNumber[1] ? `.${tokenizedNumber[1]}` : "";
return integer + decimal;
};
export default addCommas;