Home > Net >  Add trailing zeros to match precision dynamically
Add trailing zeros to match precision dynamically

Time:10-18

I am creating a react crypto project and just trying to figure out how to add trailing zeros dynamically without using the toFixed method. The reason why I am avoiding that toFixed method is because though it gets the precision right and tacks on desired trailing zeros, it rounds the number. Which can be misleading. So I am on the last part of getting this thing to operate correctly.

const getInternalAssetBalance = (selectedAsset, pairType, useFreeTotal = false) => {
    const exchangeInternalAccount = holdingsByAccount.find(account => account.exchange === 'REGULAR');
    const assetObj = exchangeInternalAccount && exchangeInternalAccount.assets.find(item => item.name === selectedAsset);
  };

I have it where it limits the digits after the decimal based on precision(meaning it won't go over the precision specified), however, if a number happens to have less decimal places than the desired precision, it won't tack on the extra trailing zeros. For example lets say we have a number 12.353. If the precision was 5, I would want the result to be 12.35300. So that it tacks on the extra two zeros.

Anyone happen to know how I can dynamically tack on zeros if the balance amount happens to have fewer decimal places than the desired precision so that it matches?

CodePudding user response:

A few remarks:

  • Since your function returns a number data type, you lose any format that wants to have trailing zeroes in the decimal part. A number value does not have any formatting that goes with it. Just like the native .toFixed method, you need to return a string.

  • You can still make use of the .toFixed method if you first make the truncation that is needed. This you can do by multiplying the number with a power of 10, truncate it to integer, and then divide it again.

function toFixed(n, precision) {
    const coeff = 10**precision;
    return (Math.floor(n * coeff) / coeff).toFixed(precision);
}

console.log(toFixed(1.234567, 4)); // 1.2345
console.log(toFixed(1.23,     4)); // 1.2300

  • Related