What's the difference between
"2" * 1 + 5
and
parseInt("2") + 5
It's just a to write a more readable code, or there are compatibility issues with the first form.
parseInt is used to grab integers from a string. Consider the following code:
var myString = "3 blind mice";
var myInteger = parseInt(myString); //3
JavaScript will do automatic type conversion, so something like this:
"2" * 1 + 5 //7
The string "2" gets converted to a number.
As noted above in the comments, parseInt takes an additional argument for the base.
JavaScript has a lot of very weird rules about type conversion, and sometimes it's not exactly clear what JavaScript will do in every situation. Keep in mind that the + operator is also used for concatenation as well as addition.
If you're trying to explicitly convert something to a number, you can use the Number constructor provided by JavaScript. Considering the following:
var myString = "2";
var myNum = Number(myString); //2
console.log(typeof myNum); //number
Without the new keyword, it can be used to convert strings to numbers. While it does work, I am not sure parseInt should be used for conversion. Just use the Number constructor.
I don't think there are compatibility issues with using coercion in the first form, it is a language feature that should be widely supported.
However, since you have to add code to do the conversion either way (* 1 vs. parseInt), I would vote for parseInt from a style perspective because it makes your intention clearer. It is hard enough sometimes to keep types straight in javascript without using implicit conversions.
Someone not familiar with your code or with javascript might wonder what is going on with that first form as well.
Plus, as indicated in the comments, parseInt is faster so it's a win all around.
Related
I thought that BigInt method and any number postfix n convention method are the same. Am I wrong? The issue explained below:
Firstly, I have summed two numbers i.e.
a = 812409329480932850928309582n;
b = 382759230958092895809328955n;
using any number postfix n convention method.
Secondly, I have summed the same numbers stored in a different variable i.e.
c = BigInt(812409329480932850928309582);
d = BigInt(382759230958092895809328955);
using BigInt method. But, the issue here is that I am getting different answers as shown in the picture. Can someone help me out here?
The parameters passed by your code to the BigInt() constructor are plain numbers, and they're beyond the range of safely-representable integers. Thus those constants are imprecise as numbers, and your resulting BigInt values are incorrect.
Using the constant syntax is the way to do it if you have the actual constant values (strings of digits).
If you really want to use the constructor, you can pass the values in as strings instead of numeric constants. The constructor will correctly parse the strings as BigInt constants.
Say I have a string, which value is already a number, e.g. var str = "1234" Now I want to convert it to number.
I have seen two tricks on the internet so far,
Use the unary +: var num = +str
Use the multiply operator *: var num = str*1
I want to know which one is better in general.
As I saw from the comment of the accepted answer here: Converting Json Results to a Date, it seems like *1 is best to be avoided. Is this true and what is the reason behind it?
Fewer operations, basically.
The unary plus calls the internal toNumber method, whereas the multiplication operator calls toNumber as well, then does a math operation on it.
Why do the extra steps?
http://www.ecma-international.org/ecma-262/6.0/#sec-unary-plus-operator
http://www.ecma-international.org/ecma-262/6.0/#sec-applying-the-mul-operator
I was wondering why do people have to convert numbers to string. What are the practical uses for that kind of conversion?
Similarly why do developers use parseInt or parseFloat to convert a string to a number.
thanks
The variable’s data type is the JavaScript scripting engine’s interpretation of the type of data that variable is currently holding. A string variable holds a string; a number variable holds a number value, and so on. However, unlike many other languages, in JavaScript, the same variable can hold different types of data, all within the same application. This is a concept known by the terms loose typing and dynamic typing, both of which mean that a JavaScript variable can hold different data types at different times depending on context.
With a loosely typed language, you don’t have to declare ahead of time that a variable will be a string or a number or a boolean, as the data type is actually determined while the application is being processed. If you start out with a string variable and then want to use it as a number, that’s perfectly fine, as long as the string actually contains something that resembles a number and not something such as an email address. If you later want to treat it as a string again, that’s fine, too.
The forgiving nature of loose typing can end up generating problems. If you try to add two numbers together, but the JavaScript engine interprets the variable holding one of them as a string data type, you end up with an odd string, rather than the sum you were expecting. Context is everything when it comes to variables and data types with JavaScript.
Using parseInt and parseFloat is important if you want to do arithmetic operations on a number which is in string form. For example
"42" + 1 === "421"
parseInt("42") + 1 === 43;
The reverse is true when you want to do string operations on values which are currently a number.
42 + 1 === 43
(42 + "") + 1 === 421
Why one would want to do the former or latter though is very scenario specific. I'd wager the case of converting strings to numbers for arithmetic operations is the more prominent case though.
An example of when converting numbers to strings is useful is when you want to format the number a certain way, perhaps like a currency (1234.56 -> $1,234.56).
The converse is useful when you want to do arithmetic on strings the represent numbers. Say you have a text box were you allow the user to input a number. The value of that text box will be a string, but you need it as a number to do some arithmetic with it, so you would use parseInt and parseFloat.
string -> number:
Think about simple number validation using JS. if you can convert a string into a number, then you can validate that number before posting to a number, or for use in an arithmetic operation.
number -> string:
String concatenation mainly and display purposes. The language will most often use implicit conversion to convert the number into a string anyway, such as:
1 + " new answer has been posted"
Do remember, Javascript is a loosely typed language. This can hide a lot of implicit type-casting that is occurring.
sorry, but i'm not that maths guy, so i do not know how it is really called:
number 12345678901234567890123 could be also stated as 1.2345678901234567890123 * 10^22 (if i'm right and did not miss any decimal...)
consider this javascript:
var number = 12345678901234567890123;
var stringValue = number.toString();
if i do so, it renders the alternative translation (mentioned above). instead i want to render simple, plain, ... 12345678901234567890123
how can this be done?
EDIT:
just to be clear: the number i want to render, does not contain any decimal places. it's just a simple 12345678901234567890123 ... not 12345678901234567890123.123 or anything likewise. and, as i'm with javascript, typeof is number
if you still want to deal with numbers on the order of 10^22 without rounding, then you should use a BigInt class, which implements arbitrary sized numbers. There are several BigInt javascript implementations you can find on the net.
I have an interesting question, I have been doing some work with javascript and a database ID came out as "3494793310847464221", now this is being entered into javascript as a number yet it is using the number as a different value, both when output to an alert and when being passed to another javascript function.
Here is some example code to show the error to its fullest.
<html><head><script language="javascript">alert( 3494793310847464221);
var rar = 3494793310847464221;
alert(rar);
</script></head></html>
This has completly baffeled me and for once google is not my friend...
btw the number is 179 more then the number there...
Your number is larger than the maximum allowed integer value in javascript (2^53). This has previously been covered by What is JavaScript's highest integer value that a Number can go to without losing precision?
In JavaScript, all numbers (even integral ones) are stored as IEEE-754 floating-point numbers. However, FPs have limited "precision" (see the Wikipedia article for more info), so your number isn't able to be represented exactly.
You will need to either store your number as a string or use some other "bignum" approach (unfortunately, I don't know of any JS bignum libraries off the top of my head).
Edit: After doing a little digging, it doesn't seem as if there's been a lot of work done in the way of JavaScript bignum libraries. In fact, the only bignum implementation of any kind that I was able to find is Edward Martin's JavaScript High Precision Calculator.
Use a string instead.
179 more is one way to look at it. Another way is, after the first 16 digits, any further digit is 0. I don't know the details, but it looks like your variable only stores up to 16 digits.
That number exceeds (2^31)-1, and that's the problem; javascript uses 32-bit signed integers (meaning, a range from –2,147,483,648 to 2,147,483,647). Your best choice is to use strings, and create functions to manipulate the strings as numbers.
I wouldn't be all too surprised, if there already was a library that does what you need.
One possible solution is to use a BigInt library such as: http://www.leemon.com/crypto/BigInt.html
This will allow you to store integers of arbitrary precision, but it will not be as fast as standard arithmetic.
Since it's to big to be stored as int, it's converted to float. In JavaScript ther is no explicit integer and float types, there's only universal Number type.
"Can't increment and decrement a string easily..."
Really?
function incr_num(x) {
var lastdigit=Number(x.charAt(x.length-1));
if (lastdigit!=9) return (x.substring(0,x.length-1))+""+(lastdigit+1);
if (x=="9") return "10";
return incr_num(x.substring(0,x.length-1))+"0";
}
function decr_num(x) {
if(x=="0") return "(error: cannot decrement zero)";
var lastdigit=Number(x.charAt(x.length-1));
if (lastdigit!=0) return (x.substring(0,x.length-1))+""+(lastdigit-1);
if (x=="10") return "9"; // delete this line if you like leading zero
return decr_num(x.substring(0,x.length-1))+"9";
}
Just guessing, but perhaps the number is stored as a floating type, and the difference might be because of some rounding error. If that is the case it might work correctly if you use another interpreter (browser, or whatever you are running it in)