Given some number of decimal places, how can I get the smallest number that matches those decimals?
E.g.
For 3 decimal places, it would be 0.001.
For 5 decimal places, it would be 0.00001.
For 0 decimal places, it would be 0
...and so on
CodePudding user response:
Math.pow
can help:
console.log(10 ** -1); // 0.1
console.log(10 ** -2); // 0.01
console.log(10 ** -3); // 0.001
So if n
is the amount of decimals you want, do Math.pow(10, -n)
copy-paste-ready function:
function smallestFractionalNumberWithDecimals(n) {
if (n <= 0) {
return 0;
}
return Math.pow(10, -n);
}
only exception is for n=0 because Math.pow(10, 0)
is 1
CodePudding user response:
The below logic can be one way to do what you want to generate:
function generate(n) {
if (n >= 0) {
return (n === 0) ? 0 : 1 / Math.pow(10, n);
}
else {
return -1;
}
}
console.log(generate(3));
console.log(generate(5));
console.log(generate(0));