How do I parse a 20-digit number using JavaScript and jQuery?
A 20-digit number is generally too big for a JavaScript native numeric type, so you'll need to find a "big number" package to use. Here's one that I've seen mentioned on Stack Overflow and that looks interesting: http://silentmatt.com/biginteger/
That one is just integers. If you need decimal fractions too, you'll have to find something else.
If you just want to check that a 20-digit string looks like a number, and you don't need to know the value, you can do that with a regular expression.
You can't have a 20-digit number in JavaScript - it'll get floated off on you.
You can keep 20 digits (or 200 or 2000) intact as a string, or as an array of digits, but to do any math on it you need a big integer object or library.
Normally you use Number() or parseInt("", [radix]) to parse a string into a real number.
I am guessing you are asking about what happens when the string you parse is above the int - threshold. In this case it greatly depends on what you are trying to accomplish.
There are some libraries that allow working with big numbers such as https://silentmatt.com/biginteger/ - see answer - (did not test it, but it looks OK). Also try searching for BigInt JavaScript or BigMath.
In short: working with VERY large number or exact decimals is a challenge in every programming language and often requires very specific mathematical libraries (which are less convenient and often a lot slower than when you work in "normal" (int/long) areas) - which obviously is not an issue when you REALLY want those big numbers.
Related
I have some logic within a function that takes a string of numbers called digits like so:
6145390195186705543
I then attempt to convert with parseInt() like so:
parseInt(digits)
The result of:
digits = parseInt(digits);
is
6145390195186705000
Can someone help me understand why this is the case? and how i can get an accurate conversion?
This is another version of "broken" floating point math: Javascript uses 64 bits to store numbers as small as the size of an atom up to the number of atoms in the universe. As that is quite a broad range it cannot be stored accurately, therefore the numbers are stored in an imprecise way but can represent a very broad range. In your case 6145390195186705000 is the inaccurate version JS is able to store as 6145390195186705543 cannot be stored.
and how i can get an accurate conversion?
You cannot store an "accurate number", therefore you cannot convert it accurately. However there are some libraries that allow you to work with strings as if they were numbers, such as BigIntJS.
As this is a common problem, this is going to be solved in the next JS version, see this proposal. You can currently test it in the new version of chrome.
I am looking for a Javascript library able to work with very, very, very big numbers (I only need a precision of a few digits after the decimal point so it should be possible) which is able to work with numbers of the form 5e+(7e+194) for example, and also print them in that form. Is there such a library out there? It would be extra sweet if it can handle as many e's as I give it (e.g. 1e+1e+...+1e+154)
This is a question I've been wondering about ever since I found the toString() function, but have never bothered to ask. Should I use basic JS or the function that does the same thing?
Now, don't get me wrong, I realize toString has its redeeming qualities, like converting a function to a string.
var message = function() {
// multi
// line
// string
}.toString();
But admit it: we mainly use toString for converting numbers to strings. Couldn't we just do this instead?
var myNumber = 1234;
var message = ''+myNumber;
Not only is this shorter, but according to JSPerf the toString method is 97% slower! (Proof: http://jsperf.com/tostring-vs-basic-js ) And as I said, I know toString is useful, but when people raise question about types of Javascript variables, toString() usually comes up. And this is, like, basic Javascript. Every browser can do quotes.
Same goes for parseInt. Now, before I discovered parseInt, I discovered that multiplying a string by one would convert it to a number. That's because you cannot multiply a string, naturally, forcing Javascript to treat it as a number.
var message = "4321";
var myNumber = message*1;
Now, interestingly, this is slower than parseInt, but not by much. I also noticed that an empty string, or one without numbers, will return 0, whereas parseInt will return NaN because there are no numbers in the string. Once again, I realize parseInt is faster and can convert to different bases. However, multiplying is shorter, will work in any browser, and parseInt, remember, will only return integers. So why does it always come up as the answer to questions, asking how to convert to numbers/what NaN is?
Now this might be going a little bit off topic, but I actually wonder a similar thing about jQuery. Once again, jQuery is something I've never really understood the use for. Javascript code is clean and jQuery is in and of itself a JS file, so it cannot do anything Javascript can't do. It may simplify certain functions and stuff, but why not just copy those functions to your page then and leave out the remaining functions you don't use? It seems overkill to include jQuery merely to complete one simple task. And animation isn't excused either here - because that too can be done with native Javascript. So why jQuery?
Ultimately what I'm asking is, why do we need these things for these purposes when there are better methods? Or are they better methods? Is using functions a better practive just in general?
Not only is this shorter, but according to JSPerf the toString method is 97% slower!
Unless you're calling .toString() on hundreds of millions of numbers every second and you've found that this is a bottleneck in your application through profiling, this should not be a factor at all.
But admit it: we mainly use toString for converting numbers to strings
As you've seen, this can be done implicitly by just adding a string and a number together, so I fail to see any benefit of using '' + n in place of n.toString(). The latter is more readable when you're not actually concatenating n with a string.
However, multiplying is shorter, will work in any browser, and parseInt, remember, will only return integers.
Are you saying that parseInt doesn't work in every browser? If you want to parse something as an integer, use parseInt. If you want to parse something as a float (JavaScript doesn't actually have a special type for either, all numbers are floats), use parseFloat.
The more common pattern is using +'123', which has the exact same behavior as 1 * '123'. parseInt handles empty strings properly, but for whatever reason does not validate strings as you'd expect. The unary plus returns NaN in case of an error, but treats whitespace and empty strings incorrectly. It's one of JavaScript's shortcomings, so there's really no concrete choice between the two if you're working in base 10.
So why does it always come up as the answer to questions, asking how to convert to numbers/what NaN is?
Because the spec included these functions to convert strings into numbers and converting strings into numbers using binary operators like you're doing is a side effect, not the primary purpose. Also you can parse integers in different bases using parseInt, which isn't possible with type coercion.
It may simplify certain functions and stuff, but why not just copy those functions to your page then and leave out the remaining functions you don't use?
If you load jQuery from a CDN, then there's a really good chance that a user's browser has already downloaded it and has it cached, making download times and bloat almost nonexistent. If you make a "custom build", I'd bet that it'll make the site slower on first load.
And animation isn't excused either here - because that too can be done with native Javascript.
So can everything. There's no point in reinventing the wheel every time you write something.
In JavaScript codes, I have seen people using '+' character to convert string to integer as in -
var i = +"2";
another way is just using parseInt() method as following -
var i = parseInt("2");
I want to know which one is efficient?
Sorry I should also add that, I am dealing with integers only and the data is huge so even a little difference in performance would be good for me.
It depends on the Browser.
i've created a nasty little Testcase for some String-To-Number conversion possibilities i know.
Ive also added possibilities to convert to floating-point-numbers, as in Javascript Numbers are Numbers, no matter if they have floating point or not.
Check it out. Corrections and suggestions appreciated!
As some other folks around here said in the comments below the question: I also think its better not to think to much about it, bu to focus on readability..
Long story short, don't worry about it, use whatever is more convinient for you and the actual case; micro-optimizations like this are useless. Id' say just remember that you might need to pass in the radix parameter into parseInt if your number is (or looks) octal or some other format.
Is there a way to represent a number with higher than 53-bit precision in JavaScript? In other words, is there a way to represent 64-bit precision number?
I am trying to implement some logic in which each bit of a 64-bit number represents something. I lose the lower significant bits when I try to set bits higher than 2^53.
Math.pow(2,53) + Math.pow(2,0) == Math.pow(2,53)
Is there a way to implement a custom library or something to achieve this?
Google's Closure library has goog.math.Long for this purpose.
The GWT team have added a long emulation support so java longs really hold 64 bits. Do you want 64 bit floats or whole numbers ?
I'd just use either an array of integers or a string.
The numbers in javascript are doubles, I think there is a rounding error involved in your equation.
Perhaps I should have added some technical detail. Basically the GWT long emulation uses a tuple of two numbers, the first holding the high 32 bits and the second the low 32 bits of the 64 bit long.
The library of course contains methods to add stuff like adding two "longs" and getting a "long" result. Within your GWT Java code it just looks like two regular longs - one doesn't need to fiddle or be aware of the tuple. By using this approach GWT avoids the problem you're probably alluding to, namely "longs" dropping the lower bits of precision which isn't acceptable in many cases.
Whilst floats are by definition imprecise / approximations of a value, a whole number like a long isn't. GWT always holds a 64 bit long - maths using such longs never use precision. The exception to this is overflows but that accurately matches what occurs in Java etc when you add two very large long values which require more than 64 bits - eg 2^32-1 + 2^32-1.
To do the same for floating point numbers will require a similar approach. You will need to have a library that uses a tuple.
The following code might work for you; I haven't tested it however yet:
BigDecimal for JavaScript
Yes, 11 bit are reserved for exponent, only 52 bits containt value also called fraction.
Javascript allows bitwise operations on numbers but only first 32 bits are used in those operations according to Javascript standard specification.
I do not understand misleading GWT/Java/long answers in Javascript/double question though? Javascript is not Java.
Why would anyone need 64 bit precision in javascript ?
Longs sometimes hold ID of stuff in a DB so its important not to lose some of the lower bits... but floating point numbers are most of the time used for calculations. To use floats to hold monetary or similar exacting values is plain wrong. If you truely need 64 bit precision do the maths on the server where its faster and so on.