Created
June 3, 2022 06:05
-
-
Save AkshatGiri/3b174f2da39b6b8370fafc1ea466f9d3 to your computer and use it in GitHub Desktop.
A function that takes in a precise eth price and truncates it make it more readable
This file contains hidden or 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
/** | |
* | |
* @param {string} price | |
* @returns {string} | |
*/ | |
function truncatePrice(price){ | |
if(!price){ | |
return '0.00' | |
} | |
const zerosArr = [] // will contain all grouped 0s from beginning of the price ( and decimal ) | |
const priceArr = [...price] // will contain all relevant digits from price after the loop. | |
while(priceArr[0] === '0' || priceArr[0] === '.'){ | |
zerosArr.push(priceArr.shift()) | |
} | |
// if there are no zeroes in the beginning of the price, lets return the original price. | |
if(zerosArr.length === 0){ | |
const [preDecimal, postDecimal] = price.split('.') | |
if(!postDecimal){ | |
return preDecimal | |
} | |
return preDecimal + '.' + postDecimal?.slice(0, 3) | |
} | |
return zerosArr.join('') + priceArr.slice(0, 3).join('') | |
} | |
function truncAndLog(price){ | |
console.log('Full Price - ', price) | |
console.log('Truncated Price - ', truncatePrice(price)) | |
console.log('-----------------------------------------') | |
} | |
truncAndLog("0.000342245989304813") // Output - 0.000342 | |
truncAndLog("4.12310239842938") // Output - 4.123 | |
truncAndLog("2.007") // Output - 2.007 | |
truncAndLog("42") // Ouput - 42 | |
truncAndLog("0") // Output - 0 | |
truncAndLog("") // Output - 0.00 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment