Division inaccurate in Javascript? [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Elegant workaround for JavaScript floating point number problem
If I perform the following operation in Javascript:
0.06120*400
The result is 24.48.
However, if I do this:
24.48/400
The result is:
0.061200000000000004
JSFiddle: http://jsfiddle.net/zcDH7/
So it appears that Javascript rounds things differently when doing division and multiplication?
Using my calculator, the operation 24.48/400 results in the correct answer of 0.0612.
How should I deal with Javascript's inaccurate division? I can't simply round the number off, because I will be dealing with numbers of varying precision.
Thanks for your advice.

You can get the correct result with simply using:
var a = 24.48/400;
console.log(a.toFixed(6));
And because typeof a.toFixed(6) === 'string' you can:
var a = 24.48/400;
console.log(parseFloat(a.toFixed(6)));
The argument of toFixed is the number of decimals you want.

Related

Extra numbers being added when decrementing value from number with JavaScript [duplicate]

This question already has answers here:
How to deal with floating point number precision in JavaScript?
(47 answers)
Closed 5 years ago.
I'm trying to decrement "0.01" from a number, it works fine the first time, but when I try to decrement one more time it adds some extra numbers.
Here is my JavaScript code:
function decrement() {
var credits_sidebar = $('#credits_sidebar').html();
var credits_update = credits_sidebar - 0.01;
$("#credits_sidebar").fadeOut('');
$("#credits_sidebar").html(credits_update);
$("#credits_sidebar").fadeIn('');
}
If you click once on the decrement button it works, but if you click another time, the number will be "95.97999999999999" it should be 95.98 instead.
Here's an example JsFiddle:
https://jsfiddle.net/rozvnay1/
var credits_update = (credits_sidebar - 0.01).toFixed(2)
JSFiddle demo: https://jsfiddle.net/8eakhn4L/1/
This is a problem with floating point value representation.
You should consider using
Math.round((credits_sidebar - 0.01)* 100)) / 100
This behavior is normal and expected because of the way floating point math is done in JavaScript.
However what you simply can do is multiply your number by a factor of 100 to make it a whole number that needs to be decremented then you can do the decrement and divide the result by 100 to get the correct decimal answer.
You need to update this for working of code:
var credits_update = (credits_sidebar - 0.01).toFixed(2);

Javascript issue with localstorage (value changing itself) [duplicate]

This question already has answers here:
What is JavaScript's highest integer value that a number can go to without losing precision?
(21 answers)
Large numbers erroneously rounded in JavaScript
(6 answers)
Closed 5 years ago.
i'm currently trying to store data via localstorage on my website, and if for example I do so :
localStorage.setItem("vue",10206726906969851)
When I want to get the value back I get this result :
localStorage.getItem("vue")
-> "10206726906969852"
So why does the value changes ? Thank you in advance for your help
JavaScript is not epic at precision with numbers. An example:
.2 + .2 = .4
but
.2 + .2 + .2 = 0.6000000000000001
The number you are using is too big for JS to maintain good precision on it. Log the following in your console and you will see what I mean.
10206726906969851 > Number.MAX_SAFE_INTEGER // returns true
The number you are using is too big. I have experienced this in the past. The server will give me numbers that are fine for Java, but too large for JavaScript. So... JS will mess them all up. The only way to fix was to get a shorter number that JS wouldn't barf on.

Javascript Prevent Automatic Rounding [duplicate]

This question already has answers here:
How to deal with floating point number precision in JavaScript?
(47 answers)
Closed 8 years ago.
I was wondering if there was any way to prevent javascript from automatically rounding my numbers. I made a program to calculate pi using the Gregory-Leibniz series. It only goes to a certain amount of decimal places. Here is my code:
pi=0;
x=1;
i=1;
function doStuff(){
pi = pi+(4/x);
x=x+2;
pi = pi-(4/x);
x=x+2;
document.getElementById("someDiv").innerHTML = pi;
}
If you are trying to work with numbers requiring precision beyond the JavaScript float (only 64 bits of precision) you could consider using a library like one of those mentioned in this question: Is there a decimal math library for JavaScript?
In particular the bignumber library looks promising for your purposes.
Here is a quick demonstration jsfiddle: http://jsfiddle.net/H88tS/
Note that the fiddle is linking in the bignumber library.
$(document).ready(function () {
BigNumber.config({ DECIMAL_PLACES : 50, ERRORS : false});
var pi = new BigNumber(0, 10),
x = new BigNumber(1, 10),
two = new BigNumber(2, 10),
four = new BigNumber(4, 10);
function iterate() {
pi = pi.plus(four.dividedBy(x));
x = x.plus(two);
pi = pi.minus(four.dividedBy(x));
x = x.plus(two);
$("#pi").text(pi.toPrecision(50));
}
$('button').click(iterate);
});
Unfortunately, it's computationally impossible to prevent rounding of a number with potentially infinite decimal places.
There are some hacks one could suggest, though, like having a class HugeNumber whose objects are lists or arrays of algarisms, or even strings that contain only numbers, and having arithmetic operations implemented in it (by yourself, of course). Unless processing efficiency is a concern, this would be an acceptable solution. Maybe something like that already exists in a plugin or even in some built-in class, I just never needed that so I really don't know.

multiply in javascript can't get correct answer [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicates:
Why 81.66 * 15 = 1224.8999999 in Javascript (or Perl) and not 1224.9 ?
Is JavaScript’s math broken?
var t1 = 5000;
var t2 = 0.07;
alert(t1 * t2);
Here is very simple code that return incorrect result;
I predict the result is 350
but the result is 350.00000000000005
How can I get correct result?
and what's wrong in this code?
Floating point arithmetic in computers is an approximation of the value.
see
http://en.wikipedia.org/wiki/Floating_point#Problems_with_floating-point
Math.round() will help you :-)
The definitive article to read is
What Every Computer Scientist Should Know About Floating-Point Arithmetic

Javascript - How to squared a number?

Using the javascript function
function squareIt(number) {
return number * number;
}
When given the number 4294967296 the function returns 18446744073709552000 is returned
Everyone knows the real answer is 18446744073709551616 :-)
I guess this is to to with rounding on my 32-bit machine. However, would this script give the right answer on a 64 bit machine? Has anyone tried this?
ChrisV- see this post. Also it easier for people to evaluate your question by typing the following JavaScript directly into the browser URL textbox:
javascript:4294967296*4294967296
what about this
function squareIt(number){
return Math.pow(number,2)
}
Javascript uses 64 bit floating point arithmetic internally for numerical calculations - the results you see are a reflection of this, and will happene regardless of the underlying architecture.
Here is one more example based on BigInteger.js.
alert(bigInt(4294967296).square());
<script src="https://cdnjs.cloudflare.com/ajax/libs/big-integer/1.6.40/BigInteger.min.js"></script>

Categories