Skip to content

Instantly share code, notes, and snippets.

@AkshatGiri
Created June 3, 2022 06:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AkshatGiri/3b174f2da39b6b8370fafc1ea466f9d3 to your computer and use it in GitHub Desktop.
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
/**
*
* @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