Format Numbers to always show only first 4 decimal numbers

Advertisements

I’m trying to print my numbers that will show only the first 4 numbers of the decimal and not everything. Unfortunately I didn’t find a solution, I tried some functions attempts but nothing worked out, it always ended up like a number that is .toFixed(4)

//Non working function for my purpose...
function formatToFourDecimals(num) {
    return (Math.round(num * 10000) / 10000).toFixed(4);
  }

  const TOSHI_price_WETH = "0.000000010528483311"; // Goal 0.00000001052
  const TOSHI_price_USD = "0.000018256390061274"; // Goal 0.00001825

  const example1 = "0.000000010528483311"; //Goal 0.00000001052
  const example2 = "0.000018256390061274"; //Goal 0.00001825
  const example3 = "0.00035256565612116112161"; //Goal 0.0003525
  const example4 = "0.0121215121313131313131313"; //Goal 0.01212

  console.log(formatToFourDecimals(example1)); // Expected 0.00000001052
  console.log(formatToFourDecimals(example2)); // Expected 0.00001825
  console.log(formatToFourDecimals(example3)); // Expected 0.0003525
  console.log(formatToFourDecimals(example4)); // Expected 0.01212

  console.log("$TOSHI price:", formatToFourDecimals(TOSHI_price_WETH), "WETH"); // Expected 0.00000001052 WETH
  console.log("$TOSHI price USD:", formatToFourDecimals(TOSHI_price_USD), "$"); // Expected 0.00001825 $

Goal:

instead of 0.000000010528483311 show 0.00000001052

instead of 0.000018256390061274 show 0.00001825

instead of 32.3232326262623 show 32.3232

etc…

Outputs:

0.0000
0.0000
0.0004
0.0121
$TOSHI price: 0.0000 WETH
$TOSHI price USD: 0.0000 $

>Solution :

toFixed(4) returns the number rounded to 4 digits after the decimal point. There’s nothing built-in that starts counting after the leading zeroes.

You can convert the number to a string, then use a regular expression to match zeroes after the decimal point and then 4 following digits.

function formatToFourDecimals(num) {
  num = String(num);
  let match = num.match(/^\d+\.0*\d{0,4}/);
  if (match) {
    return match[0];
  }
  return num;
}

const TOSHI_price_WETH = "0.000000010528483311"; // Goal 0.00000001052
const TOSHI_price_USD = "0.000018256390061274"; // Goal 0.00001825

const example1 = "0.000000010528483311"; //Goal 0.00000001052
const example2 = "0.000018256390061274"; //Goal 0.00001825
const example3 = "0.00035256565612116112161"; //Goal 0.0003525
const example4 = "0.0121215121313131313131313"; //Goal 0.01212

console.log(formatToFourDecimals(example1)); // Expected 0.00000001052
console.log(formatToFourDecimals(example2)); // Expected 0.00001825
console.log(formatToFourDecimals(example3)); // Expected 0.0003525
console.log(formatToFourDecimals(example4)); // Expected 0.01212

console.log("$TOSHI price:", formatToFourDecimals(TOSHI_price_WETH), "WETH"); // Expected 0.00000001052 WETH
console.log("$TOSHI price USD:", formatToFourDecimals(TOSHI_price_USD), "$"); // Expected 0.00001825 $

Leave a ReplyCancel reply