Finding The Smallest Increment Of A Number
Is there any built in capability in JavaScript that allows you to get the smallest increment of a certain number without expanding it? For example: var i = 0.0003412 smallest incre
Solution 1:
a different approach to parsing the value.
functionsmallestIncrement(nr) {
if (nr < 0) nr = -nr;
let str = nr.toExponential(),
e = str.indexOf("e");
returnNumber("1e" + (str.substr(e + 1) - Math.max(0, e - 2)));
}
//just for completenessfunctionbiggestIncrement(nr) {
if (nr < 0) nr = -nr;
let str = nr.toExponential();
returnNumber("1" + str.substr(str.indexOf("e")))
}
//floating point math has issues. like://0.1 + 0.2 === 0.30000000000000004functionfixFloat(v){
returnMath.round(v/1e-14)*1e-14;
}
[
0.0003412,
-3000,
12.340,
0.0000000123
].forEach(nr => {
console.log(
nr,
fixFloat(nr+smallestIncrement(nr)),
fixFloat(nr+biggestIncrement(nr))
);
})
.as-console-wrapper {
top: 0;
max-height: 100%!important
}
you stated that for values without decimal places, you want the step to be 1.
I didn't add that into the functions since I don't see, how/why there should be a difference in logic between 1.234e-10
and 1.234e+10
.
You can clamp this by performing a simple Math.min(1, smallestIncrement(nr))
or by changing the code to return Number("1e" + Math.min(0, str.substr(e + 1) - Math.max(0, e - 2)));
Solution 2:
There is no built in function for this, if that's your question. You would have to come up with a solution yourself. Something like this:
Math.pow(0.1, String(num).split('.')[1].length)
Post a Comment for "Finding The Smallest Increment Of A Number"