Javascript floating calculation error [duplicate] - javascript

This question already has answers here:
Why does floating-point arithmetic not give exact results when adding decimal fractions?
(31 answers)
Closed 10 years ago.
Here i have a problem in my web application(tested on chrome and firefox and nodejs):
when i run (1.2 - 1) it returns 0.19999999999999996 as result.
does anyone know why?

you can solve your problem:
(1.2 - 1).toFixed(1) * 1 // 0.2

you can use toFixed method of javascript more detail:
Method of Number
Implemented in JavaScript 1.5
ECMAScript Edition ECMAScript 3rd Edition
Syntax
number.toFixed( [digits] )
Parameter
digits
The number of digits to appear after the decimal point; this may be a value between 0 and 20, inclusive, and implementations may optionally support a larger range of values. If this argument is omitted, it is treated as 0.
Returns
A string representation of number that does not use exponential notation and has exactly digits digits after the decimal place. The number is rounded if necessary, and the fractional part is padded with zeros if necessary so that it has the specified length. If number is greater than 1e+21, this method simply calls Number.toString() and returns a string in exponential notation.
Throws
RangeError
If digits is too small or too large. Values between 0 and 20, inclusive, will not cause a RangeError. Implementations are allowed to support larger and smaller values as well. TypeError
If this method is invoked on an object that is not a Number.
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Number/toFixed

Related

Javascript "toLocaleString()" function chnages decimals to zero when number is very large [duplicate]

This question already has answers here:
Node.js Maximum Safe Floating-point Number
(4 answers)
What is JavaScript's highest integer value that a number can go to without losing precision?
(21 answers)
Is floating point math broken?
(31 answers)
Closed 2 years ago.
I am developing a react app and i need to format some numbers using toLocaleString function and i realize that the decimal part of the number changes to zero when the number is very
(10000.25).toLocaleString('en',{maximumFractionDigits: 2, minimumFractionDigits: 2});
//Output: 10,000.25
(10000000000000000000.25).toLocaleString('en',{maximumFractionDigits: 2, minimumFractionDigits: 2});
//Output: 10,000,000,000,000,000,000.00
why is this so? is it a bug or am I missing something?
Javascript compiler cannot handle very large numbers. Use Number.MAX_SAFE_INTEGER to check the last number it can handle. Try to consider using string type from the beginning if these numbers are not calculated (Maybe if you get it from an API kind of), or try using BigInt type.
For floating point, the maximum number it can handle to a precision of 1 decimal digit is 562949953421311 and it differs for other digits. This has been referred here. Try using the BigNumber class in your case.

Leading zeros leading to wrong sorting answer using inbuilt sort method of javascript [duplicate]

This question already has answers here:
Javascript - Leading zero to a number converting the number to some different number. not getting why this happening?
(2 answers)
Closed 5 years ago.
I was sorting a string/array of integers in lexicographical order. A case came when i had to sort a string containing "022" using array.sort. I don't know why it is equating that equal to "18" when being printed.
var l = [022,12];
l.sort();
(2) [12, 18] => output
What is the reason behind this and how to correct it?
I recommend to "use strict"; so that 022 will produce a syntax error instead of octal number:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Deprecated_octal
This isn't specific to the sort. If you just type 022 into a console, you'll get back 18. This is because 022 is being interpreted as an OctalIntegerLiteral, instead of as a DecimalLiteral. This is not always the case however. Taking a look at the documentation:
Note that decimal literals can start with a zero (0) followed by another decimal digit, but If all digits after the leading 0 are smaller than 8, the number is interpreted as an octal number. This won't throw in JavaScript, see bug 957513. See also the page about parseInt().
EDIT: To remove the leading 0s and interpret the 022 as a decimal integer, you can use parseInt and specify the base:
parseInt("022", 10);
> 22

why does javascript Number function return wrong value for this number? [duplicate]

This question already has answers here:
Large numbers erroneously rounded in JavaScript
(6 answers)
Closed 6 years ago.
so I ran into this issue with javascript Number() function, it seems to return the wrong value:
the following code:
Number("10153396863200835")
returns 10153396863200836, not 10153396863200835
but if I do Number("10153396863200836") it returns 10153396863200836
and Number("10153396863200834") returns 10153396863200834
so I'm confused what's going on? thanks
Because JavaScript's numbers are IEEE-754 double-precision binary floating point (frequently known as "double"). They have only about 15 digits of decimal precision. Your number, 10153396863200835, is much larger than that.
In doubles, the maximum whole number before we stop being able to represent the next whole number is 9,007,199,254,740,9921. 9,007,199,254,740,993 cannot be represented by doubles; 9,007,199,254,740,994 can. That's because at that scale, the least significant bit is worth 2 decimal. The further you go, the bigger those gaps get, as the least significant bit starts being worth 4 decimal, then 8, then...
Modern JavaScript has a handy constant for the value right before this value, 9,007,199,254,740,991: Number.MAX_SAFE_INTEGER. It's defined as the last whole number in a double where adding 1 gives you the next consequtive whole number. The name is slightly misleading, as 9,007,199,254,740,994 or indeed 10,153,396,863,200,836 aren't going to suddenly stop having those values, it's just that math with them starts getting...interesting.

Why does parsing a large number, of string form, give a larger number? [duplicate]

This question already has answers here:
Why do JavaScript converts some number values automatically
(5 answers)
Closed 7 years ago.
See snippet:
var num = "9223372036854775808";
document.write(num);
document.write("<br>");
document.write(parseInt(num, 10));
On running the code snippet, the first write yields:
9223372036854775808
and the third write yields:
9223372036854776000
But, I am only parsing the number in string form to number. Why does it give a still larger number?
I thought it might have to do something with limits of storage capacity, but then, why would it yield a larger number if it could not store the smaller?
I read this question: Why parsing a very large number to integer return 1 and the parseInt doc but they did not help much.
So, Why does parsing a large number, of string form, return a larger number?
The first result is fine as it is treated as a string.
In the second one, it crosses the value of int which is +/- 9007199254740992 ie, the maximum value which parseint can parse is 9007199254740992 and since your value 9223372036854775808 is larger than the maximum value. it is giving some garbage value.
As commented correctly by blunderboy it seems that that the reason could be this
The numbers in Javascript are 64 bit "double" precision which follow the IEE754 floating point. Sothe largest positive whole number that can therefore be accurately represented is 2^53 and the rest of the remaining bits are reserved for the exponent.
If you check the ECMA specs this has been explained.

lint warning: parseInt missing radix parameter [duplicate]

This question already has answers here:
JSLint says "missing radix parameter"
(11 answers)
Closed 9 years ago.
I have the following code that gives the warning described in the title:
year: parseInt(dateParts[0]),
......................^
Any help is much appreciated
See the manual for parseInt; it takes 2 arguments. The second one tells it which number base you want to use. This is almost always going to be 10 (decimal).
parseInt(dateParts[0],10)
If you don't specify it, then it will be inferred from the data.
If radix is undefined or 0 (or absent), JavaScript assumes the following:
If the input string begins with "0x" or "0X", radix is 16
(hexadecimal) and the remainder of the string is parsed.
If the input string begins with "0", radix is eight (octal) or 10
(decimal). Exactly which radix is chosen is implementation-dependent.
ECMAScript 5 specifies that 10 (decimal) is used, but not all browsers
support this yet. For this reason always specify a radix when using
parseInt.
If the input string begins with any other value, the radix is 10
(decimal).
Some years after I wrote the above, things have changed. Now:
The ECMAScript 5 specification of the function parseInt no longer allows implementations to treat Strings beginning with a 0 character as octal values. Many implementations have adopted this behavior as of 2021.
… but you still should use a radix, at least for browser side code, because not all implementations have caught up.

Categories

Resources