1
let number = 0.0000000123456

I want this number as 0.000000123. Basically, I want 3 characters after last 0. Numbers of zeros are not constant and can vary and the length of numbers after zeros can also vary.

Yash Sharma
  • 232
  • 2
  • 12
  • 1
    Please show what you tried. Tip: the results of [Math.log10(...)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/log10) will help to calculate where the first non-zero digit is located. – Peter B Apr 17 '22 at 12:05

2 Answers2

2

The way I would do it would be

  • Transforming the number to a string (using for example this answer from StackOverflow)
  • Splitting the number with 0 to get the number of 0 after coma (which is the length of the array minus 2)
  • Fixing the number with the toFixed method with the number of 0 after coma + 3

function toPlainString(num) {
  return ('' + +num).replace(/(-?)(\d*)\.?(\d*)e([+-]\d+)/,
    function(a, b, c, d, e) {
      return e < 0 ?
        b + '0.' + Array(1 - e - c.length).join(0) + c + d :
        b + c + d + Array(e - d.length + 1).join(0);
    });
}

function toFixedAfterZeros(number, length) {
  const numberToString = toPlainString(number)
  const nbZeros = numberToString.split('0')
  const nbZerosAfterComa = nbZeros.length - 2 > 0 ? nbZeros.length - 2 : 0
  return number.toFixed(nbZerosAfterComa + 3)
}

console.log(toFixedAfterZeros(0.00000021612621, 3))
console.log(toFixedAfterZeros(0.00000021, 3))
console.log(toFixedAfterZeros(1.1, 3))
console.log(toFixedAfterZeros(210, 3))
console.log(toFixedAfterZeros(-12, 3))

Using one line : number.toFixed(toPlainString(number).split('0').length - 2 + 3)

RenaudC5
  • 3,553
  • 1
  • 11
  • 29
1

function makeIt(n){
  return n.toFixed(20).match(/^-?\d*\.?0*\d{0,3}/)[0];
}

console.log(makeIt(0.00000041123215));
console.log(makeIt(0.23215));
console.log(makeIt(-0.00023215));
console.log(makeIt(500));
Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
JamalThaBoss
  • 336
  • 2
  • 7