How decimals are calculated in javascript - javascript

I have to do some calculation in decimals in my application using javascript but the result
is unexpected.
The result of the below statement is 1.707 [as expected]
var total=1.17+0.237+0.3;
also when we add the numbers below, I am getting 0.7070000000000001 [unexpected]
var totalnew=0.17+0.237+0.3;
Also, the expression (0.1+0.2===0.3) returns false[unexpected], but (1.1+0.2===1.3) returns true[as expected] .
Why is this happening and what is the workaround for this.

Floating point is notoriously tricky. Basically it boils down to that there are an infinite amount of values between two real numbers, so it is impossible to represent them correctly in a computer.
If you want to print the number i suggest:
total.toFixed();
Which will always give you three decimal places. And when you want to check if two floats are the same you need to do something like this:
function nearlyEqual(a, b, epsilon) {
var absA = Math.abs(a);
var absB = Math.abs(b);
var diff = Math.abs(a - b);
var minNormal = 1.1754943508222875e-38;
if (a == b) { // shortcut, handles infinities
return true;
} else if (a == 0 || b == 0 || diff < minNormal) {
// a or b is zero or both are extremely close to it
// relative error is less meaningful here
return diff < (epsilon * minNormal);
} else { // use relative error
return diff / (absA + absB) < epsilon;
}
}
nearlyEqual(0.1+0.2, 0.3, 0.0001);
As is suggested here How should I do floating point comparison?

This is because the values have no fixed precision. To resolve this, try implementing Math.Round.
Math.round((0.17 + 0.237 + 0.3) * 1e12) / 1e12

Related

How to get closest floating point number that is less/greater than a given number

Here is a sample function:
function step(x, min, max) {
return x >= min && x <= max ? x : 0;
}
console.log(step(-3 - Number.EPSILON, -3, 5)); // Expected 0, actual -3
console.log(step(5 + Number.EPSILON, -3, 5)); // Expected 0, actual 5
I need to check, that it returns zero for values outside [min, max] interval. For sure I can subtract/add a bigger number, for example 1. But I'm pretty sure, that there should exist a function returning previous/next floating point number. Could you please suggest the function or how to implement it?
Not all adjacent representable numbers are the same mathematical distance from one another. Floating point arcana isn't my strong suit, but if you want to find the next representable number, I think you need to keep increasing what you add/subtract from it by Number.EPSILON for as long as you keep getting the same number.
The very naive, simplistic approach would look like this (but keep reading):
// DON'T USE THIS
function next(x) {
const ep = x < 0 ? -Number.EPSILON : Number.EPSILON;
let adder = ep;
let result;
do {
result = x + adder;
adder += ep;
} while (result === x);
return result;
}
console.log(`Next for -3: ${next(-3)}`);
console.log(`Next for 5: ${next(5)}`);
(That's assuming direction based on the sign of the number given, which is probably not what you really want, but is easily switched up.)
But, that would take hours (at least) to handle next(Number.MAX_SAFE_INTEGER).
When I posted my caveat on the above originally, I said a better approach would take the magnitude of x into account "...or do bit twiddling (which definitely takes us into floating point arcana land)..." and you pointed to Java's Math.nextAfter operation, so I had to find out what they do. And indeed, it's bit twiddling, and it's wonderfully simple. Here's a re-implementation of the OpenJDK's version from here (the line number in that link will rot):
// A JavaScript implementation of OpenJDK's `Double.nextAfter` method.
function nextAfter(start, direction) {
// These arrays share their underlying memory, letting us use them to do what
// Java's `Double.doubleToRawLongBits` and `Double.longBitsToDouble` do.
const f64 = new Float64Array(1);
const b64 = new BigInt64Array(f64.buffer);
// Comments from https://github.com/openjdk/jdk/blob/master/src/java.base/share/classes/java/lang/Math.java:
/*
* The cases:
*
* nextAfter(+infinity, 0) == MAX_VALUE
* nextAfter(+infinity, +infinity) == +infinity
* nextAfter(-infinity, 0) == -MAX_VALUE
* nextAfter(-infinity, -infinity) == -infinity
*
* are naturally handled without any additional testing
*/
/*
* IEEE 754 floating-point numbers are lexicographically
* ordered if treated as signed-magnitude integers.
* Since Java's integers are two's complement,
* incrementing the two's complement representation of a
* logically negative floating-point value *decrements*
* the signed-magnitude representation. Therefore, when
* the integer representation of a floating-point value
* is negative, the adjustment to the representation is in
* the opposite direction from what would initially be expected.
*/
// Branch to descending case first as it is more costly than ascending
// case due to start != 0.0d conditional.
if (start > direction) {
// descending
if (start !== 0) {
f64[0] = start;
const transducer = b64[0];
b64[0] = transducer + (transducer > 0n ? -1n : 1n);
return f64[0];
} else {
// start == 0.0d && direction < 0.0d
return -Number.MIN_VALUE;
}
} else if (start < direction) {
// ascending
// Add +0.0 to get rid of a -0.0 (+0.0 + -0.0 => +0.0)
// then bitwise convert start to integer.
f64[0] = start + 0;
const transducer = b64[0];
b64[0] = transducer + (transducer >= 0n ? 1n : -1n);
return f64[0];
} else if (start == direction) {
return direction;
} else {
// isNaN(start) || isNaN(direction)
return start + direction;
}
}
function test(start, direction) {
const result = nextAfter(start, direction);
console.log(`${start} ${direction > 0 ? "up" : "down"} is ${result}`);
}
test(-3, -Infinity);
test(5, Infinity);
test(Number.MAX_SAFE_INTEGER, Infinity);
test(Number.MAX_SAFE_INTEGER + 2, Infinity);

Get next smallest nearest number to a decimal

Introduction
For some calculations I need to find the smallest possible number I can add/subtract from a specified number without JavaScript getting in trouble with the internal used data type.
Goal
I tried to write a function which is able to return the next nearest number to VALUE in the direction of value DIR.
function nextNearest(value, direction) {
// Special cases for value==0 or value==direction removed
if (direction < value) {
return value - Number.MIN_VALUE;
} else {
return value + Number.MIN_VALUE;
}
}
The problem with this is, that JavaScript uses a 64-bit float type (I think) which has different minimum step sizes depending on its current exponent.
Problem in detail
The problem is the step size depending on its current exponent:
var a = Number.MIN_VALUE;
console.log(a);
// 5e-324
console.log(a + Number.MIN_VALUE);
// 1e-323 (changed, as expected)
var a = Number.MAX_VALUE;
console.log(a);
// 1.7976931348623157e+308
console.log(a - Number.MIN_VALUE);
// 1.7976931348623157e+308 (that's wrong)
console.log(a - Number.MIN_VALUE == a);
// true (which also is wrong)
Summary
So how can I find the smallest possible number I can add/subtract from a value specified in a parameter in any direction? In C++ this would be easily possible by accessing the numbers binary values.
I tried to implement Pointy's suggestion from the comments (using typed arrays). This is loosely adapted from glibc's implementation of nextafter. Should be good enough.
You can actually just increment/decrement the 64-bit integer representation of a double to get the wanted result. A mantissa overflow will overflow to the exponent which happens to be just what you want.
Since JavaScript doesn't provide a Uint64Array I had to implement a manual overflow over two 32-bit integers.
This works on little-endian architectures, but I've left out big-endian since I have no way to test it. If you need this to work on big-endian architectures you'll have to adapt this code.
// Return the next representable double from value towards direction
function nextNearest(value, direction) {
if (typeof value != "number" || typeof direction != "number")
return NaN;
if (isNaN(value) || isNaN(direction))
return NaN;
if (!isFinite(value))
return value;
if (value === direction)
return value;
var buffer = new ArrayBuffer(8);
var f64 = new Float64Array(buffer);
var u32 = new Uint32Array(buffer);
f64[0] = value;
if (value === 0) {
u32[0] = 1;
u32[1] = direction < 0 ? 1 << 31 : 0;
} else if ((value > 0) && (value < direction) || (value < 0) && (value > direction)) {
if (u32[0]++ === 0xFFFFFFFF)
u32[1]++;
} else {
if (u32[0]-- === 0)
u32[1]--;
}
return f64[0];
}
var testCases = [0, 1, -1, 0.1,
-1, 10, 42e42,
0.9999999999999999, 1.0000000000000002,
10.00000762939453, // overflows between dwords
5e-324, -5e-324, // minimum subnormals (around zero)
Number.MAX_VALUE, -Number.MAX_VALUE,
Infinity, -Infinity, NaN];
document.write("<table><tr><th>n</th><th>next</th><th>prev</th></tr>");
testCases.forEach(function(n) {
var next = nextNearest(n, Infinity);
var prev = nextNearest(n, -Infinity);
document.write("<tr><td>" + n + "</td><td>" + next + "</td><td>" + prev + "</td></tr>");
});
document.write("</table>");
Number.MIN_VALUE is the smallest possible representable number, not the smallest possible difference between representable numbers. Because of the way javascript handles floating point numbers the smallest possible difference between representable numbers changes with the size of the number. As the number gets larger the precision gets smaller. Thus there is no one number that will solve your problem. I suggest you either rethink how you're going to solve your problem or choose a subset of numbers to use and not the full range of MAX and MIN values.
for example: 1.7976931348623156e+308 == 1.7976931348623155e+308 //true
Also, by subtracting MIN_VALUE from MAX_VALUE you're trying to get javascript to accurately represent a number with over 600 significant figures. That's a bit too much.
To find the (smallest) increment value of a given float:
For example, useful to set the step attribute of an html input type=number on the fly!
function getIncrement(number) {
function getDecimals(number) {
let d = parseFloat(number).toString().split('.')[1]
if (d) {return d.length}
return 0
}
return (0 + "." + Array(getDecimals(number)-1).fill(0).join("") + "1").toLocaleString('fullwide', {useGrouping:false})
}
// Tests
console.log(
getIncrement(0.00000105),
getIncrement(455.105),
getIncrement(455.050000)
)
// Test
// Create input type number
function createInput(value){
let p = document.createElement("input")
p.type = "number"
p.step = getIncrement(value)
p.min = 0
p.max = 1000
p.value = value
panel.appendChild(p)
}
// Tests
createInput(0.00000105)
createInput(455.105)
createInput(455.050000)
<b>TEST.</b><br>
<div id="panel"></div>
The step attribute is set based on the base value increment.
<hr>
<b>TEST DEFAULT BEHAVIOR. </b><br>
<input type="number" min="0" max="100" value="0.00000105">
<input type="number" step="0.001" min="0" max="100" value="0.00000105">
<input type="number" step="0.000001" min="0" max="100" value="0.00000105">
<br>
This is not usable. The step atttribute needs to be set based on the value it will contains. But this require to know the value in advance and if a new dynamic value has a different decimal place, it become also unusable.
Get only the decimal place.
function getDecimalplace(number) {
let d = parseFloat(number).toString().split('.')[1]
return d.length
}
// Tests
console.log(
getDecimalplace(8.0001) // 4
)
console.log(
getDecimalplace(4.555433) // 6
)
Here's a quick and dirty method using Math.log2() that doesn't require heap allocation and is much faster:
function getNext(num) {
return num + 2 ** (Math.log2(num) - 52);
}
or
function getPrevious(num) {
return num - 2 ** (Math.log2(num) - 52);
}
The disadvantage is that it's not perfect, just very close. It doesn't work well for absurdly small values as a result. (num < 2 ** -1000)
It's possible that there's failure case for a number > 9.332636185032189e-302, but I haven't found one. There are failure cases for numbers smaller than the above, for example:
console.log(getNext(Number.MIN_VALUE) === Number.MIN_VALUE); // true
However, the following works just fine:
let counter = 0;
// 2 ** -1000 === 9.332636185032189e-302
for (let i = -1000; i < 1000; i += 0.00001) {
counter++;
if (getNext(2 ** i) === 2 ** i)
throw 'err';
if (getPrevious(2 ** i) === 2 ** i)
throw 'err';
}
console.log(counter.toLocaleString()); // 200,000,001
But note that "a bunch of test cases work" is not a proof of correctness.
If you don't want the hacky way,
function precision( n ) {
return Math.max( Number.MIN_VALUE, 2 ** Math.floor( Math.log2( n ) ) * Number.EPSILON )
}
works aswell.
This gives you the increment to the next (larger absolute value) floating point number. Stepping to zero always works as the precision increases.
Since Number.EPSILON is the floating point precision at n=1, we can from this calculate all epsilon values by using 2**x and log2() this function will return the smallest safe increment from a number for all floating point numbers.
Only edge case are denormalized numbers (smaller than 2**-1023) where the step will be larger.

Calculating cubic root for negative number

So, to be short,
3√(-8) = (-8)1/3
console.log(Math.pow(-8,1/3));
//Should be -2
But when I test it out, it outputs
NaN
Why? Is it a bug or it is expected to be like this in the first place? I am using JavaScript to draw graphs, but this messes up the graph.
You can use this snippet to calculate it. It also works for other powers, e.g. 1/4, 1/5, etc.
function nthroot(x, n) {
try {
var negate = n % 2 == 1 && x < 0;
if(negate)
x = -x;
var possible = Math.pow(x, 1 / n);
n = Math.pow(possible, n);
if(Math.abs(x - n) < 1 && (x > 0 == n > 0))
return negate ? -possible : possible;
} catch(e){}
}
nthroot(-8, 3);
Source: http://gotochriswest.com/blog/2011/05/06/cube-root-an-beyond/
A faster approach for just calculating the cubic root:
Math.cbrt = function(x) {
var sign = x === 0 ? 0 : x > 0 ? 1 : -1;
return sign * Math.pow(Math.abs(x), 1 / 3);
}
Math.cbrt(-8);
Update
To find an integer based cubic root, you can use the following function, inspired by this answer:
// positive-only cubic root approximation
function cbrt(n)
{
var a = n; // note: this is a non optimized assumption
while (a * a * a > n) {
a = Math.floor((2 * a + (n / (a * a))) / 3);
}
return a;
}
It starts with an assumption that converges to the closest integer a for which a^3 <= n. This function can be adjusted in the same way to support a negative base.
There's no bug; you are raising a negative number to a fractional power; hence, the NaN.
The top hit on google for this is from Dr Math the explanation is pretty good. It says for for real numbers (not complex numbers anyway), a negative number raised to a fractional power may not be a real number. The simplest example is probably
-4 ^ (1/2)
which is essentially computing the square root of -4. Even though the cubic root of -8 does have real solutions, I think that most software libraries find it more efficient not to do all the complex arithmetic and return NaN only when the imaginary part is nonzero and give you the nice real answer otherwise.
EDIT
Just to make absolutely clear that NaN is the intended result, see the official ECMAScript 5.1 Specification, Section 15.8.2.13. It says:
If x<0 and x is finite and y is finite and y is not an integer, the result is NaN.
Again, even though SOME instances of raising negative numbers to fractional powers have exactly one real root, many languages just do the NaN thing for all cases of negative numbers to fractional roots.
Please do not think JavaScript is the only such language. C++ does the same thing:
If x is finite negative and y is finite but not an integer value, it causes a domain error.
Two key problems:
Mathematically, there are multiple cubic roots of a negative number: -2, but also 2 complex roots (see cube roots of unity).
Javascript's Math object (and most other standard math libraries) will not do fractional powers of negative numbers. It converts the fractional power to a float before the function receives it, so you are asking the function to compute a floating point power of a negative number, which may or may not have a real solution. So it does the pragmatic thing and refuses to attempt to calculate such a value.
If you want to get the correct answer, you'll need to decide how mathematically correct you want to be, and write those rules into a non-standard implementation of pow.
All library functions are limited to avoid excessive calculation times and unnecessary complexity.
I like the other answers, but how about overriding Math.pow so it would be able to work with all nth roots of negative numbers:
//keep the original method for proxying
Math.pow_ = Math.pow;
//redefine the method
Math.pow = function(_base, _exponent) {
if (_base < 0) {
if (Math.abs(_exponent) < 1) {
//we're calculating nth root of _base, where n === 1/_exponent
if (1 / _exponent % 2 === 0) {
//nth root of a negative number is imaginary when n is even, we could return
//a string like "123i" but this would completely mess up further computation
return NaN;
}/*else if (1 / _exponent % 2 !== 0)*/
//nth root of a negative number when n is odd
return -Math.pow_(Math.abs(_base), _exponent);
}
}/*else if (_base >=0)*/
//run the original method, nothing will go wrong
return Math.pow_(_base, _exponent);
};
Fiddled with some test cases, give me a shout if you spot a bug!
So I see a bunch of methods that revolve around Math.pow(...) which is cool, but based on the wording of the bounty I'm proposing a slightly different approach.
There are several computational approximations for solving roots, some taking quicker steps than others. Ultimately the stopping point comes down to the degree of precision desired(it's really up to you/the problem being solved).
I'm not going to explain the math in fine detail, but the following are implementations of cubed root approximations that passed the target test(bounty test - also added negative range, because of the question title). Each iteration in the loop (see the while(Math.abs(xi-xi0)>precision) loops in each method) gets a step closer to the desired precision. Once precision is achieved a format is applied to the number so it's as precise as the calculation derived from the iteration.
var precision = 0.0000000000001;
function test_cuberoot_fn(fn) {
var tested = 0,
failed = 0;
for (var i = -100; i < 100; i++) {
var root = fn(i*i*i);
if (i !== root) {
console.log(i, root);
failed++;
}
tested++;
}
if (failed) {
console.log("failed %d / %d", failed, tested);
}else{
console.log("Passed test");
}
}
test_cuberoot_fn(newtonMethod);
test_cuberoot_fn(halleysMethod);
Newton's approximation Implementation
function newtonMethod(cube){
if(cube == 0){//only John Skeet and Chuck Norris
return 0; //can divide by zero, we'll have
} //to settle for check and return
var xi = 1;
var xi0 = -1;
while(Math.abs(xi-xi0)>precision){//precision = 0.0000000000001
xi0=xi;
xi = (1/3)*((cube/(xi*xi))+2*xi);
}
return Number(xi.toPrecision(12));
}
Halley's approximation Implementation
note Halley's approximation takes quicker steps to solving the cube, so it's computationally faster than newton's approximation.
function halleysMethod(cube){
if(cube == 0){//only John Skeet and Chuck Norris
return 0; //can divide by zero, we'll have
} //to settle for check and return
var xi = 1;
var xi0 = -1;
while(Math.abs(xi-xi0)>precision){//precision = 0.0000000000001
xi0=xi;
xi = xi*((xi*xi*xi + 2*cube)/(2*xi*xi*xi+cube));
}
return Number(xi.toPrecision(12));
}
It's Working in Chrome Console
function cubeRoot(number) {
var num = number;
var temp = 1;
var inverse = 1 / 3;
if (num < 0) {
num = -num;
temp = -1;
}
var res = Math.pow(num, inverse);
var acc = res - Math.floor(res);
if (acc <= 0.00001)
res = Math.floor(res);
else if (acc >= 0.99999)
res = Math.ceil(res);
return (temp * res);
}
cubeRoot(-64) // -4
cubeRoot(64) // 4
As a heads up, in ES6 there is now a Math.cbrt function.
In my testing in Google chrome it appears to work almost twice as fast as Math.pow. Interestingly I had to add up the results otherwise chrome did a better job of optimizing away the pow function.
//do a performance test on the cube root function from es6
var start=0, end=0, k=0;
start = performance.now();
k=0;
for (var i=0.0; i<10000000.0; i+=1.0)
{
var j = Math.cbrt(i);
//k+=j;
}
end = performance.now();
console.log("cbrt took:" + (end-start),k);
k=0;
start = performance.now();
for (var i=0.0; i<10000000.0; i+=1.0)
{
var j = Math.pow(i,0.33333333);
//k+=j;
}
end = performance.now();
console.log("pow took:" + (end-start),k);
k=0;
start = performance.now();
for (var i=0.0; i<10000000.0; i+=1.0)
{
var j = Math.cbrt(i);
k+=j;
}
end = performance.now();
console.log("cbrt took:" + (end-start),k);
k=0;
start = performance.now();
for (var i=0.0; i<10000000.0; i+=1.0)
{
var j = Math.pow(i,0.33333333);
k+=j;
}
end = performance.now();
console.log("pow took:" + (end-start),k);
Result:
cbrt took:468.28200000163633 0
pow took:77.21999999921536 0
cbrt took:546.8039999977918 1615825909.5248165
pow took:869.1149999940535 1615825826.7510242
//aren't cube roots of negative numbers the same as positive, except for the sign?
Math.cubeRoot= function(n, r){
var sign= (n<0)? -1: 1;
return sign*Math.pow(Math.abs(n), 1/3);
}
Math.cubeRoot(-8)
/* returned value: (Number)
-2
*/
Just want to highlight that in ES6 there is a native cubic root function. So you can just do this (check the support here)
Math.cbrt(-8) will return you -2
this works with negative number and negative exponent:
function nthRoot(x = 0, r = 1) {
if (x < 0) {
if (r % 2 === 1) return -nthRoot(-x, r)
if (r % 2 === -1) return -1 / nthRoot(-x, -r)
}
return x ** (1 / r)
}
examples:
nthRoot( 16, 2) 4
nthRoot( 16, -2) 0.25
nthRoot(-16, 2) NaN
nthRoot(-16, -2) NaN
nthRoot( 27, 3) 3
nthRoot( 27, -3) 0.3333333333333333
nthRoot(-27, 3) -3
nthRoot(-27, -3) -0.3333333333333333

How do I get the decimal places of a floating point number in Javascript?

What I would like to have is the almost opposite of Number.prototype.toPrecision(), meaning that when i have number, how many decimals does it have? E.g.
(12.3456).getDecimals() // 4
For anyone wondering how to do this faster (without converting to string), here's a solution:
function precision(a) {
var e = 1;
while (Math.round(a * e) / e !== a) e *= 10;
return Math.log(e) / Math.LN10;
}
Edit: a more complete solution with edge cases covered:
function precision(a) {
if (!isFinite(a)) return 0;
var e = 1, p = 0;
while (Math.round(a * e) / e !== a) { e *= 10; p++; }
return p;
}
One possible solution (depends on the application):
var precision = (12.3456 + "").split(".")[1].length;
If by "precision" you mean "decimal places", then that's impossible because floats are binary. They don't have decimal places, and most values that have a small number of decimal places have recurring digits in binary, and when they're translated back to decimal that doesn't necessarily yield the original decimal number.
Any code that works with the "decimal places" of a float is liable to produce unexpected results on some numbers.
There is no native function to determine the number of decimals. What you can do is convert the number to string and then count the offset off the decimal delimiter .:
Number.prototype.getPrecision = function() {
var s = this + "",
d = s.indexOf('.') + 1;
return !d ? 0 : s.length - d;
};
(123).getPrecision() === 0;
(123.0).getPrecision() === 0;
(123.12345).getPrecision() === 5;
(1e3).getPrecision() === 0;
(1e-3).getPrecision() === 3;
But it's in the nature of floats to fool you. 1 may just as well be represented by 0.00000000989 or something. I'm not sure how well the above actually performs in real life applications.
Basing on #blackpla9ue comment and considering numbers exponential format:
function getPrecision (num) {
var numAsStr = num.toFixed(10); //number can be presented in exponential format, avoid it
numAsStr = numAsStr.replace(/0+$/g, '');
var precision = String(numAsStr).replace('.', '').length - num.toFixed().length;
return precision;
}
getPrecision(12.3456); //4
getPrecision(120.30003300000); //6, trailing zeros are truncated
getPrecision(15); //0
getPrecision(120.000)) //0
getPrecision(0.0000005); //7
getPrecision(-0.01)) //2
Try the following
function countDecimalPlaces(number) {
var str = "" + number;
var index = str.indexOf('.');
if (index >= 0) {
return str.length - index - 1;
} else {
return 0;
}
}
Based on #boolean_Type's method of handling exponents, but avoiding the regex:
function getPrecision (value) {
if (!isFinite(value)) { return 0; }
const [int, float = ''] = Number(value).toFixed(12).split('.');
let precision = float.length;
while (float[precision - 1] === '0' && precision >= 0) precision--;
return precision;
}
Here are a couple of examples, one that uses a library (BigNumber.js), and another that doesn't use a library. Assume you want to check that a given input number (inputNumber) has an amount of decimal places that is less than or equal to a maximum amount of decimal places (tokenDecimals).
With BigNumber.js
import BigNumber from 'bignumber.js'; // ES6
// const BigNumber = require('bignumber.js').default; // CommonJS
const tokenDecimals = 18;
const inputNumber = 0.000000000000000001;
// Convert to BigNumber
const inputNumberBn = new BigNumber(inputNumber);
// BigNumber.js API Docs: http://mikemcl.github.io/bignumber.js/#dp
console.log(`Invalid?: ${inputNumberBn.dp() > tokenDecimals}`);
Without BigNumber.js
function getPrecision(numberAsString) {
var n = numberAsString.toString().split('.');
return n.length > 1
? n[1].length
: 0;
}
const tokenDecimals = 18;
const inputNumber = 0.000000000000000001;
// Conversion of number to string returns scientific conversion
// So obtain the decimal places from the scientific notation value
const inputNumberDecimalPlaces = inputNumber.toString().split('-')[1];
// Use `toFixed` to convert the number to a string without it being
// in scientific notation and with the correct number decimal places
const inputNumberAsString = inputNumber.toFixed(inputNumberDecimalPlaces);
// Check if inputNumber is invalid due to having more decimal places
// than the permitted decimal places of the token
console.log(`Invalid?: ${getPrecision(inputNumberAsString) > tokenDecimals}`);
Assuming number is valid.
let number = 0.999;
let noOfPlaces = number.includes(".") //includes or contains
? number.toString().split(".").pop().length
: 0;
5622890.31 ops/s (91.58% slower):
function precision (n) {
return (n.toString().split('.')[1] || '').length
}
precision(1.0123456789)
33004904.53 ops/s (50.58% slower):
function precision (n) {
let e = 1
let p = 0
while(Math.round(n * e) / e !== n) {
e *= 10
p++
}
return p
}
precision(1.0123456789)
62610550.04 ops/s (6.25% slower):
function precision (n) {
let cur = n
let p = 0
while(!Number.isInteger(cur)) {
cur *= 10
p++
}
return p
}
precision(1.0123456789)
66786361.47 ops/s (fastest):
function precision (n) {
let cur = n
let p = 0
while(Math.floor(cur) !== cur) {
cur *= 10
p++
}
return p
}
precision(1.0123456789)
Here is a simple solution
First of all, if you pass a simple float value as 12.1234 then most of the below/above logics may work but if you pass a value as 12.12340, then it may exclude a count of 0. For e.g, if the value is 12.12340 then it may give you a result of 4 instead of 5. As per your problem statement, if you ask javascript to split and count your float value into 2 integers then it won't include trailing 0s of it.
Let's satisfy our requirement here with a trick ;)
In the below function you need to pass a value in string format and it will do your work
function getPrecision(value){
a = value.toString()
console.log('a ->',a)
b = a.split('.')
console.log('b->',b)
return b[1].length
getPrecision('12.12340') // Call a function
For an example, run the below logic
value = '12.12340'
a = value.toString()
b = a.split('.')
console.log('count of trailing decimals->',b[1].length)
That's it! It will give you the exact count for normal float values as well as the float values with trailing 0s!
Thank you!
This answer adds to Mourner's accepted solution by making the function more robust. As noted by many, floating point precision makes such a function unreliable. For example, precision(0.1+0.2) yields 17 rather than 1 (this might be computer specific, but for this example see https://jsfiddle.net/s0v17jby/5/).
IMHO, there are two ways around this: 1. either properly define a decimal type, using e.g. https://github.com/MikeMcl/decimal.js/, or 2. define an acceptable precision level which is both OK for your use case and not a problem for the js Number representation (8 bytes can safely represent a total of 16 digits AFAICT). For the latter workaround, one can write a more robust variant of the proposed function:
const MAX_DECIMAL_PRECISION = 9; /* must be <= 15 */
const maxDecimalPrecisionFloat = 10**MAX_DECIMAL_PRECISION;
function precisionRobust(a) {
if (!isFinite(a)) return 0;
var e = 1, p = 0;
while ( ++p<=MAX_DECIMAL_PRECISION && Math.round( ( Math.round(a * e) / e - a ) * maxDecimalPrecisionFloat ) !== 0) e *= 10;
return p-1;
}
In the above example, the maximum precision of 9 means this accepts up to 6 digits before the decimal point and 9 after (so this would work for numbers less than one million and with a maximum of 9 decimal points). If your use-case numbers are smaller then you can choose to make this precision even greater (but with a maximum of 15). It turns out that, for calculating precision, this function seems to do OK on larger numbers as well (though that would no longer be the case if we were, say, adding two rounded numbers within the precisionRobust function).
Finally, since we now know the maximum useable precision, we can further avoid infinite loops (which I have not been able to replicate but which still seem to cause problems for some).

Round number up to the nearest multiple of 3

How would I go about rounded a number up the nearest multiple of 3?
i.e.
25 would return 27
1 would return 3
0 would return 3
6 would return 6
if(n > 0)
return Math.ceil(n/3.0) * 3;
else if( n < 0)
return Math.floor(n/3.0) * 3;
else
return 3;
Simply:
3.0*Math.ceil(n/3.0)
?
Here you are!
Number.prototype.roundTo = function(num) {
var resto = this%num;
if (resto <= (num/2)) {
return this-resto;
} else {
return this+num-resto;
}
}
Examples:
y = 236.32;
x = y.roundTo(10);
// results in x = 240
y = 236.32;
x = y.roundTo(5);
// results in x = 235
I'm answering this in psuedocode since I program mainly in SystemVerilog and Vera (ASIC HDL). % represents a modulus function.
round_number_up_to_nearest_divisor = number + ((divisor - (number % divisor)) % divisor)
This works in any case.
The modulus of the number calculates the remainder, subtracting that from the divisor results in the number required to get to the next divisor multiple, then the "magic" occurs. You would think that it's good enough to have the single modulus function, but in the case where the number is an exact multiple of the divisor, it calculates an extra multiple. ie, 24 would return 27. The additional modulus protects against this by making the addition 0.
As mentioned in a comment to the accepted answer, you can just use this:
Math.ceil(x/3)*3
(Even though it does not return 3 when x is 0, because that was likely a mistake by the OP.)
Out of the nine answers posted before this one (that have not been deleted or that do not have such a low score that they are not visible to all users), only the ones by Dean Nicholson (excepting the issue with loss of significance) and beauburrier are correct. The accepted answer gives the wrong result for negative numbers and it adds an exception for 0 to account for what was likely a mistake by the OP. Two other answers round a number to the nearest multiple instead of always rounding up, one more gives the wrong result for negative numbers, and three more even give the wrong result for positive numbers.
This function will round up to the nearest multiple of whatever factor you provide.
It will not round up 0 or numbers which are already multiples.
round_up = function(x,factor){ return x - (x%factor) + (x%factor>0 && factor);}
round_up(25,3)
27
round up(1,3)
3
round_up(0,3)
0
round_up(6,3)
6
The behavior for 0 is not what you asked for, but seems more consistent and useful this way. If you did want to round up 0 though, the following function would do that:
round_up = function(x,factor){ return x - (x%factor) + ( (x%factor>0 || x==0) && factor);}
round_up(25,3)
27
round up(1,3)
3
round_up(0,3)
3
round_up(6,3)
6
Building on #Makram's approach, and incorporating #Adam's subsequent comments, I've modified the original Math.prototype example such that it accurately rounds negative numbers in both zero-centric and unbiased systems:
Number.prototype.mround = function(_mult, _zero) {
var bias = _zero || false;
var base = Math.abs(this);
var mult = Math.abs(_mult);
if (bias == true) {
base = Math.round(base / mult) * _mult;
base = (this<0)?-base:base ;
} else {
base = Math.round(this / _mult) * _mult;
}
return parseFloat(base.toFixed(_mult.precision()));
}
Number.prototype.precision = function() {
if (!isFinite(this)) return 0;
var a = this, e = 1, p = 0;
while (Math.round(a * e) / e !== a) { a *= 10; p++; }
return p;
}
Examples:
(-2).mround(3) returns -3;
(0).mround(3) returns 0;
(2).mround(3) returns 3;
(25.4).mround(3) returns 24;
(15.12).mround(.1) returns 15.1
(n - n mod 3)+3
$(document).ready(function() {
var modulus = 3;
for (i=0; i < 21; i++) {
$("#results").append("<li>" + roundUp(i, modulus) + "</li>")
}
});
function roundUp(number, modulus) {
var remainder = number % modulus;
if (remainder == 0) {
return number;
} else {
return number + modulus - remainder;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Round up to nearest multiple of 3:
<ul id="results">
</ul>
A more general answer that might help somebody with a more general problem: if you want to round numbers to multiples of a fraction, consider using a library. This is a valid use case in GUI where decimals are typed into input and for instance you want to coerce them to multiples of 0.25, 0.2, 0.5 etc. Then the naive approach won't get you far:
function roundToStep(value, step) {
return Math.round(value / step) * step;
}
console.log(roundToStep(1.005, 0.01)); // 1, and should be 1.01
After hours of trying to write up my own function and looking up npm packages, I decided that Decimal.js gets the job done right away. It even has a toNearest method that does exactly that, and you can choose whether to round up, down, or to closer value (default).
const Decimal = require("decimal.js")
function roundToStep (value, step) {
return new Decimal(value).toNearest(step).toNumber();
}
console.log(roundToStep(1.005, 0.01)); // 1.01
RunKit example
Using remainder operator (modulus):
(n - 1 - (n - 1) % 3) + 3
By the code given below use can change any numbers and you can find any multiple of any number
let numbers = [8,11,15];
let multiple = 3
let result = numbers.map(myFunction);
function myFunction(n){
let answer = Math.round(n/multiple) * multiple ;
if (answer <= 0)
return multiple
else
return answer
}
console.log("Closest Multiple of " + multiple + " is " + result);
if(x%3==0)
return x
else
return ((x/3|0)+1)*3

Categories

Resources