Round number with lots of decimal places in Javascript - javascript

I have a number with an extreme amount of decimal places.
1.5583255870000002e+36
I'm struggling to find a good way to round this down to 2 decimal places using JavaScript.
I've tried a few variations using parseFloat() Math.round() and .toFixed().
Here is an example using .toPrecision().
App.currentUSDBalance = Number((App.currentBalance * App.maticPrice).toPrecision(2));
The result is 1.6e+36. I was hoping for something like 1.59.
Thanks,

The following snippet should be the answer to your updated question:
const yourNumber=1.234567890123e36, ndigits=3;
// returns two variations of the solution:
function mySigDig(num,dig){
return [+(num/(10**Math.floor(Math.log10(num)))).toPrecision(dig),
+num.toPrecision(dig).replace(/e.*/,"")]
}
console.log(mySigDig(23,ndigits));
console.log(mySigDig(2345678,ndigits));
console.log(mySigDig(yourNumber,ndigits));

Apologies for the terrible question.
I ended up solving this by converting to string and dropping the e+X.
App.currentUSDBalance = Number((App.currentBalance * App.maticPrice).toPrecision(3)).toString().split('e')[0];
Thanks for the help.

Related

Adding a whole number and a decimal in Javascript results in removal of the decimal?

I'm sure this is simple, but in my javascript code, I have two numbers. One contains a decimal, and the other doesn't, and I add them together (ie. 7.5 + 5), I am getting a result with NO decimal value.
Do I need to cast each number variable as a double? I know that all numbers are doubles in javascript - which is why I do not understand this behavior...
For instance, I have var answer = week1 + week2;. Does this make sense?
Thanks in advance!
I am sorry for wasting time - turns out I was using parseInt instead of parseFloat to gather the "week" values I spoke about.
Can someone please close this question or delete it? Before the shame consumes me?

Alternate function of math.pow in JavaScript

I am using Math.pow() function in my code but when I try to execute below condition, this function return infinity which is not required. I am looking for an alternate solutions.
math.pow(451939.27436410653, 299);
Please help if anyone any idea
Use logs
What result were you expecting? The result is extremely large and exceeds the ability of the conventional floating point format to represent. I would be surprised if this was really necessary in a real-world calculation. Can you provide some context?
If really necessary, perhaps you could resolve the difficulties by using logarithms. If y=Math.pow(451939,299) then
Math.log(y) = Math.log(451939) * 299.
You could do any multiplication/division by adding/subtracting logs, and then do a Math.exp at the end to generate your result.
This may be easier than using a special library like bignumber.js for arbitrary-precision arithmetic. For example, the code below returns "7.395117980030695 x 10^ 1690", which has 1691 digits before the decimal point.
let log10Y=Math.log(451939.27436410653)*299/Math.log(10);
let b = Math.floor(log10Y);
let a = log10Y-b;
console.log("Answer: ",10**a," x 10^",b);
If you want to store such enormous numbers, you can use a library like bignumber.js. It stores floating-point values with an exponent as large as necessary to store them.

toFixed javascript function giving strange results?

I am trying to fix the number to 2 digits after decimal and for that i am using toFixedfunction of javascript. Below are the strange results i am getting, please check and help me.
var number = 11.995;
number.toFixed(2); // giving me 11.99 which is correct
var number = 19.995;
number.toFixed(2); // giving me 20.00 which is incorrect
Can anyone tell me why it is happening.
Thanks for your help.
This is how floating point math works. The value 19.995 is not exact binary (base 2). To make it more clear, think of an exact number when you divide 10/3.
For more in-depth explanations, read this: http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html
In your case you can work with strings instead (at least it seems like that is what you want):
number.toString().substr(0, n);
Or define a function like this (made in 2 minutes, just an example):
Number.toFixed = function(no, n) {
var spl = no.toString().split('.');
if ( spl.length > 1 ) {
return spl[0]+'.'+spl[1].substr(0,n);
}
return spl[0];
}
Number.toFixed(19.995, 2); // 19.99
toFixed rounds the value. Since 19.995 is exactly halfway between 19.99 and 20.00, it has to choose one of them. Traditionally, rounding prefers the even result (this prevents bias, since round-ups and round-downs will be equal).
I have create a function which done all for me..
function toFixed(number, precision) {
var multiplier = Math.pow(10, precision + 1),
wholeNumber = Math.floor(number * multiplier);
return Math.round(wholeNumber / 10) * 10 / multiplier;
}
//Call this function to retrive exect value
toFixed((+adjustmentval), 2);
David has answered your doubt I'm guessing. Just providing an alternate solution here.
You can use the Math.floor() method of the Math object for this.
Something like this, Math.floor(number*100)/100
Can anyone tell me why it is happening.
The IEEE-754 double-precision binary floating point number standard used by JavaScript's number type (and similar times in several other languages) does not perfectly store all numbers, it stores some numbers imprecisely, in a way that lets it A) Store them in just 64 bits, and B) Calculate with them quickly.
For 11.995, the actual value is 11.99499988555908203125, just slightly less than 11.995.
For 19.995, the actual value is 19.9950008392333984375, just slightly more than 19.995.
That explains why when you round them using the usual round-to-nearest-half-up operation, 11.995 (which is really 11.99499988555908203125) rounds down to 11.99 but 19.995 (which is really 19.9950008392333984375) rounds up to 20.00.
(This site has a handy calculator for visualizing this stuff.)
More here on SO:
Is floating point math broken?
How to deal with floating point number precision in JavaScript?

Javascript issue with math calculations

Why is it if I do this in javascript, I get the following result:
1234.56 * 10 = 12345.599999999999
It should be 123456. How can I get around this problem?
Thanks.
Floating points are not exact, since there are ifinite numbers at their range [or in any range to be more exact], and only a finite number of bits to store this data.
Have a look at what every programmer should know about floating point arithmetics.
Another easy solution:
parseFloat((1234.56 * 10).toPrecision(12))
and the result will be: 12345.6, and YES... it works with decimal numbers.
As the others said, floating points and so on.
Easy solution would be to do something like this:
var answer = parseInt(1234.56 * 10);
Or just use Math.round?
All numbers in JS are internally defined by float and drop the less significant digits if needed.
(10000000000000000000000000000 + 1) == 10000000000000000000000000000
// this will return true
And javascript is well known for droping bits quite often in numbers. So handle with care

Is there a way to truncate scientific notation numbers in Javascript?

As you all know since it is one of the most asked topic on SO, I am having problems with rounding errors (it isn't actually errors, I am well aware).
Instead of explaining my point, I'll give an example of what possible numbers I have and which input I want to be able to obtain:
Let's say
var a = 15 * 1e-9;
alert(a)
outputs
1.5000000000000002e-8
I want to be able to obtain 1.5e-8 instead, but I cannot just multiply by 10e8, round and divide by 10e8 because I don't know if it will be e-8 or e-45 or anything else.
So basically I want to be able to obtain the 1.5000002 part, apply toFixed(3) and put back the exponent part.
I could convert into a string and parse but it just doesn't seem right...
Any idea ?
(I apologize in advance if you feel this is one of many duplicates, but I could not find a similar question, only related ones)
Gael
You can use the toPrecision method:
var a = 15 * 1e-9;
a.toPrecision(2); // "1.5e-8"
If you're doing scientific work and need to round with significant figures in mind: Rounding to an arbitrary number of significant digits
var a = 15 * 1e-9;
console.log(Number.parseFloat(a).toExponential(2));
//the above formula will display the result in the console as: "1.50e-8"

Categories

Resources