Format Value Util Function

May 14, 2023

Util Functions

Format Value Util Function

Thuta Sann

Thuta Sann

This Format Value Util Function will return with the Units string of the number value


Share This Snippet To :

This Format Value Util Function will return with the Units string of the number value. For Example - if the value is 4000 then the return value is 4K.
/** * Format Value * @param { number } num - Number From Server * @returns { string } Formatted Value */ export const formatValue = (num) => { const formatedNum = num.toString().replace(/[^0-9.]/g, ''); if (formatedNum < 1000) { return num; } let scientificNumber = [ { v: 1e3, s: 'K' }, { v: 1e6, s: 'M' }, { v: 1e9, s: 'B' }, { v: 1e12, s: 'T' }, { v: 1e15, s: 'P' }, { v: 1e18, s: 'E' }, ]; let index; for (index = scientificNumber.length - 1; index > 0; index--) { if (num >= scientificNumber[index].v) { break; } } return ( (num / scientificNumber[index].v) .toFixed(2) .replace(/\.0+$|(\.[0-9]*[1-9])0+$/, '$1') + scientificNumber[index].s ); }; // Usage const fV = formatValue(4000);

Cookie

I baked some cookies that you have to accept, if you want to enjoy my portfolio.
In order to gather information and make improvements, I should use some third-party cookies too, Can I?