Last update: 1.11.2015

Often there is a need to convert one data to another. For example:

varnumber1 = "46"; varnumber2 = "4"; varresult = number1 + number2; console log(result); //464

Both variables represent strings, more specifically string representations of numbers. And as a result, we will get not the number 50, but the string 464. But it would be nice if they could also be added, subtracted, in general, work like with ordinary numbers.

In this case, we can use transform operations. The function is used to convert a string to a number. parseInt():

varnumber1 = "46"; varnumber2 = "4"; var result = parseInt(number1) + parseInt(number2); console log(result); // fifty

To convert strings to fractional numbers applied function parseFloat():

varnumber1 = "46.07"; varnumber2 = "4.98"; var result = parseFloat(number1) + parseFloat(number2); console log(result); //51.05

In this case, the string can have mixed content, for example, "123hello", that is, in this case there are numbers, but there are also ordinary characters. But the parseInt() method will still try to do the conversion:

Varnum1 = "123hello"; varnum2 = parseInt(num1); console log(num2); // 123

If the method fails to convert, it returns NaN (Not a Number), which indicates that the string does not represent a number and cannot be converted.

With special function isNaN() you can check if a string represents a number. If the string is not a number, then the function returns true, if it is a number, then false:

Var num1 = "javascript"; varnum2 = "22"; varresult = isNaN(num1); console log(result); // true - num1 is not a number result = isNaN(num2); console log(result); // false - num2 is a number

Above, we considered the translation of strings into numbers in decimal system. However, we can translate numbers into any system. By default, the JavaScript interpreter itself guesses which number system we want to convert the string to (usually, the decimal system is selected). But we can use the second parameter to explicitly indicate that we want to convert a string to a number on a specific system. For example, converting to a number in binary system:

Varnum1 = "110"; varnum2 = parseInt(num1, 2); console log(num2); // 6

The result will be 6, since 110 in binary is the number 6 in decimal.

Now let's write small program, in which we use operations with variables:

JavaScript

With the help of the prompt() function, a dialog box is displayed in the browser asking you to enter some value. The second argument to this function specifies the value to be used by default.

However, the prompt() function returns a string. Therefore, we need to convert this string to a number in order to perform operations with it.

After opening the page in the browser, we will see an invitation to enter the deposit amount:

Then a similar message will be displayed for entering the percentage. And at the end, the program will receive the data, convert it to numbers, and perform the calculation.

JavaScript is a language with dynamic data typing. This means that you can write values ​​to the same variable various types, while the type of the variable itself will change. This behavior often makes it possible to forget about the different behavior of variables with different type, but it is still necessary to remember this feature. Let's show this in the following example.

console.log(sum(1, 2)); // 3 (everything is ok here) console.log(sum(1, "2")); // 12 (and not so much here)

As you can see from the example, the function sum behaves incorrectly if at least one of its arguments is not a number. The fact is that when “adding” a number to a string, the number is converted to a string and it is concatenated (glued) with the second operand.

To avoid such complications, you can find out the type of a variable during script execution and correct its behavior, or carefully monitor the types of variables.

typeof operator

This unary operator takes absolutely any value as an operand and returns its type in a string variable.

JavaScript has the following data types:

// 1.) object console. log (typeof ( ) ) ; // object var p = ( x: 1 , y: 3 ) ; console. log (typeof p) ; // object // 2.) function function sayHello() ( console.log ("Hello!" ) ; ) console.log (typeof sayHello) ; // function // 3.) string console.log (typeof "JavaScript" ) ; // string // 4.) number console.log (typeof 3.1415 ) ; // number // 5.) boolean console.log (typeof true ) ; // boolean // 6.) undefined var notExistsOne; console.log (typeof notExistsOne) ; // undefined console. log (typeof notExistsTwo) ; // undefined

// 1.) object console.log(typeof()); // object var p = (x: 1, y: 3); console.log(typeofp); // object // 2.) function function sayHello() ( console.log("Hello!"); ) console.log(typeof sayHello); // function // 3.) string console.log(typeof "JavaScript"); // string // 4.) number console.log(typeof 3.1415); // number // 5.) boolean console.log(typeof true); // boolean // 6.) undefined var notExistsOne; console.log(typeof notExistsOne); // undefined console.log(typeof notExistsTwo); // undefined

note that undefined it is also a data type that consists of a single value.

Cast

Type casting in programming is the conversion of a value of a variable of one type to a value of another type.
Often this transformation occurs without the programmer's control. This can be seen in the example with the function sum. A type change occurs when the result of performing an operation on a variable of the original type is not clear. For example, it is impossible to say exactly what will result from adding a string with a number, but the operation of adding two numbers is obvious, and in this case it is logical to bring the number to the string.

Convert string to number

Sometimes the programmer himself can change the type of a variable by applying some operations to it. For example, increment or decrement operations on a string will convert it to a number.

var c = "not-a-number"; ++c; console.log(typeof c); // NaN

It is worth noting that you do not need to resort to this method of converting a string to a number because of its poor readability and non-obviousness. There are built-in functions in js for this task. parseInt and parseFloat. They take as their first argument a string to be converted to a number, and as their optional second argument, they take the base of the number system that contains the number in the string passed as the first argument. If the second argument is not specified, then it will be considered that the string contains a number in the decimal number system.

Function parseInt is used to convert a string to an integer, and the function parseFloat to convert to fractional.

var a = parseInt("10") ; console. log ([ "a = " , a, "; typeof a:" , typeof a] .join (" " ) ) ; // a = 10 ; typeof a: number var pi = parseInt("3.1415" ) ; console.log("pi = " + pi) ; // pi = 3 pi = parseFloat("3.1415" ) ; console.log("pi = " + pi) ; // pi = 3.1415

var a = parseInt("10"); console.log(["a = ", a, "; typeof a:", typeof a].join(" ")); // a = 10 ; typeof a: number var pi = parseInt("3.1415"); console.log("pi = " + pi); // pi = 3 pi = parseFloat("3.1415"); console.log("pi = " + pi); // pi = 3.1415

Note that the string can contain any literal numeric value, including hexadecimal, octal, or exponential.

a = parseInt("010") ; console.log("a = " + a) ; // a = 8 a = parseInt("0xAA" ) ; console.log("a = " + a) ; // a = 170 a = parseFloat("1e-10" ) ; console.log("a = " + a) ; // a = 1e-10 (1e-10 = 1 * 10^-10 = 0.0000000001)

a = parseInt("010"); console.log("a = " + a); // a = 8 a = parseInt("0xAA"); console.log("a = " + a); // a = 170 a = parseFloat("1e-10"); console.log("a = " + a); // a = 1e-10 (1e-10 = 1 * 10^-10 = 0.0000000001)

As the second parameter of the functions parseInt and parseFloat you can specify the base of the number system.

a = parseInt("10" , 8 ) ; console.log("a = " + a) ; // a = 8 a = parseInt("010" , 10 ) ; console.log("a = " + a) ; // a = 10 a = parseInt("ff" , 16 ) ; console.log("a = " + a) ; // a = 255

a = parseInt("10", 8); console.log("a = " + a); // a = 8 a = parseInt("010", 10); console.log("a = " + a); // a = 10 a = parseInt("ff", 16); console.log("a = " + a); // a = 255

If the value is in the string, which the functions parseInt and parseFloat take as the first parameter, is not a numeric literal, then the result of executing these functions will be the value NaN.

a = parseInt("not a number") ; console.log("a = " + a) ; // a = NaN a = parseFloat("not a number" ) ; console.log("a = " + a) ; // a = NaN

a = parseInt("not a number"); console.log("a = " + a); // a = NaN a = parseFloat("not a number"); console.log("a = " + a); // a = NaN

String conversion

AT JavaScript value any type can be cast to a string. It has already been said above that when a string is concatenated with a number, the number is reduced to a string, and only then does the concatenation take place. This will happen with any value type.

var str = "Object: " + ( ) ; console log (str) ; // Object: str = "Array: " + [ 1 , 2 , 3 ] ; console log (str) ; // Array: 1,2,3 function sum(a, b) ( return a + b; ) str = "Function: " + sum; console log (str) ; /* Function: function sum(a, b) ( return a + b; ) */

var str = "Object: " + (); console log(str); // Object: str = "Array: " + ; console log(str); // Array: 1,2,3 function sum(a, b) ( return a + b; ) str = "Function: " + sum; console log(str); /* Function: function sum(a, b) ( return a + b; ) */

In fact, when casting an object to a string, the method is implicitly called toString, which can also be called explicitly.

var p = ( x: 2 , y: 4 ) , str; str = p.toString(); console. log (typeof str) ; // string console.log (str) ; // str = [ 1 , 2 , 3 ] .toString () ; console. log (typeof str) ; // string console.log (str) ; // 1,2,3

var p = (x: 2, y: 4), str; str = p.toString(); console.log(typeofstr); // string console.log(str); // str = .toString(); console.log(typeofstr); // string console.log(str); // 1,2,3

Numeric Conversion

The conversion to a number occurs when executing mathematical operations and when performing a comparison operation with type casting (==, !=), while the value false and an empty array are converted to a value of type 0 number.

var a = true + true + true; // 1 + 1 + 1 console.log(a); // 3

A non-empty array, object, and function are cast to a string when used in arithmetic expressions.

var arr = [ 1 , 2 , 3 ] ; console.log (arr + 4 ) ; // 1,2,34 function sum(a, b) ( return a + b; ) console.log (sum + 5 ) ; // function sum(a, b)(return a + b;)5

var arr = ; console.log(arr + 4); // 1,2,34 function sum(a, b)(return a + b;) console.log(sum + 5); // function sum(a, b)(return a + b;)5

As you can see, implicit type conversion in js is far from always obvious, so you should avoid it by using functions for explicit type conversion, such as parseInt, parseFloat and toString.

That's all. As always, good luck to you!

There are two main ways to convert string to number in javascript. One way is to parse it and another way is to change its type to a number. All the tricks in other answers (e.g. unary plus) imply implicit coercion of string type to number. You can also do the same with the Number function.

Syntactic

Var parsed = parseInt("97", 10);

ParseInt and parseFloat are two functions that are used to parse strings into numbers. Parsing will stop silently if it hits a character it doesn't recognize, which can be useful for parsing strings like "92px", but it's also somewhat dangerous as it won't give you any error on bad input, instead you "will return NaN if the string doesn't start with a number. The space at the beginning of the string is ignored. Here's an example of something that does something else you want, and doesn't give any indication that things went wrong:

Var widgetsSold = parseInt("97,800", 10); // widgetsSold is now 97

It's good practice to always specify decimal as the second argument. In older browsers, if a string started at 0, it would be interpreted as octal unless a radix value was specified, which caught a lot of people by surprise. The behavior for hex start is triggered if the string starts with 0x unless a radix value is specified. 0xff. The standard actually changed with ecmascript 5 so modern browsers no longer run octals when there is a leading 0 if no reason is specified. parseInt understands radicals up to base 36, in which case both uppercase and lowercase letters are treated as equivalent.

Change string type to number

All of the other tricks mentioned above that don't use ParseInt involve implicitly coercing a string into a number. I prefer to do it explicitly

Var cast = Number("97");

This is different from parsing methods (although it still ignores spaces). It's more strict: if it doesn't understand the entire string than it returns NaN , so you can't use it for strings like 97px . Because you want a primitive number, not a Number wrapper object, make sure you don't precede the Number function with new .

Obviously converting to a number gives a value which can be a float rather than an integer, so if you want an integer you need to change it. There are several ways to do this:

Varrounded = Math.floor(Number("97.654")); // other options are Math.ceil, Math.round var fixed = Number("97.654").toFixed(0); // rounded rather than truncated var bitwised = Number("97.654")|0; // do not use for large numbers

Any bitwise operator (here I did a bitwise or, but you can also do a double negation as in the previous answer or Bitshift) will convert the value to a 32-bit integer, and most will convert to a signed integer. Please note that this won't want you to search for large integers. If an integer cannot be represented in 32 bits, it will be completed.

~~"3000000000.654" === -1294967296 // This is the same as Number("3000000000.654")|0 "3000000000.654" >>> 0 === 3000000000 // unsigned right shift gives you an extra bit "300000000000.654" > >> 0 === 3647256576 // but still fails with larger numbers

To work correctly with large numbers, you must use the rounding methods

Math.floor("3000000000.654") === 3000000000 // This is the same as Math.floor(Number("3000000000.654"))

Keep in mind that all of these methods understand exponential notation, so 2e2 is 200 , not NaN. Also, Number understands "Infinity" while parsing methods don't.

Custom

It's unlikely that either of these methods does exactly what you want. For example, I usually want a parse failure error, and I don't need Infinity support, exponents, or leading spaces. Depending on your usage, sometimes it makes sense to write a custom conversion function.

Always check that the number output or one of the parsing methods is the kind of expected number. You'll almost certainly want to use isNaN to make sure the number isn't NaN (usually the only way to know if the parse failed).

It doesn't matter what type of variable is used in the expression. If the expression is mathematical, all its variables will automatically be interpreted as numeric. If strings are processed, then all "participants" of the expression are treated as strings. However, the task of converting JavaScript "string to number" exists in a much broader context.

JavaScript Methods for Converting Strings to Numbers

The arsenal of methods for converting strings to numbers is not great, but sufficient in all simple cases. Here JavaScript (for beginners especially) is the way from simple to complex with practical examples.

You will be interested:

The example describes four different strings. In the first output block, the type of each variable function typeof is defined as string. Each string is then very simply converted to a number. In the second output block, you can see the changes in the variables after the conversion, their type has become a number. The JavaScript parseFloat conversion example is especially revealing: it was "12e+3", now it's "12000".

Changes when converting a string to a number can be significant! But only the first characters matter: they must be numeric. If there are no numeric characters, the result will be NaN.

The reverse conversion of a string that "becomes" a number is not always the same string. This moment can be used to check the correctness of entering numerical information.