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.
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.
The way I would do it would be
toFixed
method with the number of 0 after coma + 3function 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)
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));