JS Row conversion. JavaScript: Data Type Conversion

| |

In JavaScript, the data is divided into types, which helps group data and determine which values \u200b\u200bcan be assigned and what operations can be performed.

Although due to the type of JavaScript types, many values \u200b\u200bare automatically converted, to achieve the expected results, it is best to convert data types manually.

This manual will teach the converting javaScript data types, including numbers, rows and logical elements.

Implicit conversion

JavaScript programming language is very well coping with the processing of unexpected values. JavaScript does not deviate unexpected values, and trying to convert. This implicit conversion is also called Type Coercion.

Separate methods automatically convert values \u200b\u200bto use them. The Alert () method takes the string as its parameter, and other types automatically converts into strings. Thus, a numerical value can be transferred to this method:

If you run this string, the browser will return the pop-up window with a value of 8.5, which will be already converted into the string.

Using lines consisting of numbers, together with mathematical operators, you will find that JavaScript can process values \u200b\u200bimplicitly transforming lines in numbers:

// Subdument
"15" - "10";
5
// Module
"15" % "10";
5

But not all operators work predictably. This is especially true of the operator +: it additions the numbers and concatenation of strings.

// When working with rows + performs concatenation
"2" + "3";
"23"

Since the + operator has many destinations, in this example it perceives the values \u200b\u200b2 and 3 as string, despite the fact that they are expressed by numeric rows. Therefore, it combines the lines "2" and "3" and receives 23, and does not fold 2 and 3 and gets 5.

Such ambiguity takes place in the code and sometimes causes unexpected results, therefore, it is better to explicitly convert data types. This will help in support code and error processing.

Convert values \u200b\u200bin strings

To explicitly convert the value to the string, call the String () or N.Tostring () method.

Try to convert the logical value True to the string using String ().

This will return the string literal "TRUE".

You can also try to transfer the function function:

She will return the string literal:

Now try using string () with variable. Assign the numeric value of the ODYSSEY variable and use the TypeOf statement to check the type.

let Odyssey \u003d 2001;
Console.log (Typeof Odyssey);
Number

On the this moment The ODYSSEY variable is assigned a numeric value of 2001. The TypeOF operator confirms that the value is a number.

Now assign an Odyssey variable to its equivalent inside the String () function, and then use the TypeOF to ensure that the variable value is successfully converted from among the row.

oDYSSEY \u003d STRING (ODYSSEY); // "2001"
Console.log (Typeof Odyssey);
String

As you can see, now the variable ODYSSEY contains a string.

The n.tostring () function works in the same way. Replace N variable.

let BowS \u003d 400;
blas.tostring ();

Variable Brews will contain a string.

Instead of a variable, you can put the value in parentheses:

(1776) .tostring (); // Returns "1776"
(false) .tostring (); // Returns "False"
(100 + 200) .tostring (); // Returns "300"

String () and N.Tostring () clearly convert logical and numeric values \u200b\u200binto the string.

Transformation of values \u200b\u200bin numbers

The Number () method can convert the value to the number. Often there is a need to convert strings consisting of numbers, but sometimes you need to convert and logical values.

For example, send the Number () method to such a string:

The string will be converted to the number and will no longer be enclosed in quotes.

You can also assign a string of a variable and then convert it.

let Dalmatians \u003d "101";
Number (Dalmatians);
101

The string literal "101" was transformed into the number 101.

Rows from spaces or empty lines will be converted to the number 0.

Number (""); // Returns 0.
Number (""); // Returns 0.

Keep in mind that lines that do not consist of numbers are converted to NaN, which means not a number. This applies to the numbers separated by spaces.

Number ("Twelve"); // Returns Nan.
Number ("20,000"); // Returns Nan.
Number ("2 3"); // Returns Nan.
Number ("11-11-11"); // Returns Nan.

In logical data, the value of False will be 0, and True will be equal to 1.

Convert values \u200b\u200bto logical values

To convert numbers or strings to logical values, the Boolean () method is used. For example, it helps to determine if the user enters the data into the text field or not.

Any value that is interpreted as empty, for example, a number 0, an empty string, undefined, Nan or NULL values \u200b\u200bare converted to False.

Boolean (0); // Returns False.
Boolean (""); // Returns False.
Boolean (undefined); // Returns False.
Boolean (NAN); // Returns False.
Boolean (NULL); // Returns False.

Other values, including string literals consisting of spaces, will be converted to True.

Boolean (2000); // Returns True.
Boolean (""); // Returns True.
Boolean ("Maniacs"); // Returns True.

Please note: the string literal "0" is transformed into TRUE, since it is not an empty value:

Boolean ("0"); // Returns True.

Convert numbers and rows to logical values \u200b\u200ballows you to evaluate the data in binary system and can be used to control the flow in programs.

Conclusion

Now you know how JavaScript converts data types. Often due to the type of type, the data is converted implicitly that it may cause unexpected values. It is recommended to explicitly convert data types to ensure the correct operation of the programs.

In JavaScript, the values \u200b\u200bare sufficiently freely (explicitly and implicitly) can be converted from one type to another. For example, if any operator expects to get a value of a specific type, and it is transmitted to the value of another type, the interpreter will automatically try to perform the transformations to the desired type:

Console.log (10 + "machines"); // "10 cars". The number is implicitly converted to the string Console.log ("7" * "4"); // 28. Both lines are implicitly converted into numbers.

Implicit conversion - This is when the interpreter automatically performs the conversion of types, i.e. without the participation of the programmer. Explicit conversion - This is when the transformation performs the programmer itself. Explicit transformation otherwise called by bringing types:

Console.log ("7" * "4"); // 28. Implicit conversion Console.log (Number ("7") * Number ("4")); // 28. Explicit Transformation

The table below describes how to convert values \u200b\u200bfrom one type to the other in JavaScript. Blank cells correspond to situations where the transformation is not required:

Value Convert to:
Line Number Boolean An object
undefined.
nULL
"undefined"
"NULL"
Nan.
0
false
false
typeerror error
typeerror error
true.
false
"TRUE"
"false"
1
0
new Boolean (True)
nEW BOOLEAN (FALSE)
"" (empty line)
"1.2"
"One"
"-10"
"+10"
"011"
"0xFF"
0
1.2
Nan.
-10
10
11
255
false
true.
true.
true.
true.
true.
true.
new String (")
nEW STRING ("1.2")
nEW STRING ("ONE")
nEW STRING ("- 10")
nEW STRING ("+ 10")
nEW STRING ("011")
nEW STRING ("0xFF")
0
-0
Nan.
Infinity.
-INFINITY.
3
"0"
"0"
"Nan"
"Infinity"
"-INFINITY"
"3"
false
false
false
true.
true.
true.
nEW NUMBER (0)
nEW NUMBER (-0)
nEW NUMBER (NAN)
nEW NUMBER (INFINITY)
nEW Number (-infinity)
nEW NUMBER (3)
() (any object)

(Empty array)
(1 numeric element)
aRR (any other array)
function () () (any function)

see object transformation

""
"9"
see object transformation
see object transformation

see object transformation
0
9
Nan.
Nan.
true.

true.
true.
true.
true.

For explicit conversion to simple types, the following functions are used: boolean (), Number (), String (). When implicit conversion, the interpreter uses the same functions as used for explicit conversion.

For explicit conversion, you can use operators instead of functions. For example, if one of the operator's operands + is a string, then another operand is also converted to the string. The unary operator + converts its operand to the number. Unary operator! Converts the operand to a logical value and inverts it. All this was the reason for the appearance of the following peculiar ways to transform types that can be found in practice:

X + "" // The same as String (X) + X // the same as Number (x). You can also meet x - 0 !! x // Same as boolean (x)

Transformation into numbers

The Number () function converts values \u200b\u200bto the following rules:

  • Logical values \u200b\u200bTrue and False are converted to 1 and 0, respectively.
  • Numbers are returned unchanged.
  • NULL value is converted to 0.
  • Undefined value is converted to NAN.

For strings, there are special rules:

  • If the string contains only numbers with an initial sign + or - either without a sign, it is always converted to a whole decimal number. The initial zeros are ignored, for example, "0011" is transformed into 11.
  • If the string is a floating point number with an initial sign + or - either without a sign, it is converted to an appropriate floating point number (initial zeros are also ignored).
  • If the string is a number in hexadecimal format, it is converted to an appropriate whole decimal number.
  • If the string is empty, it is converted to 0.
  • If the string contains something different from previous options, it is converted to NAN.
  • The ValueOF () method is called for objects, and the value returned to them is automatically converted to previous rules. If this conversion gives as a result of NAN, the TOSTRING () method is called and the rules conversion rules are applied.

Unary operators + and work on the same rules as the Number () function.

Conversion to Boolean Values

The BOOLEAN () function converts the value to its logical equivalent:

  • The following values \u200b\u200bas a result of the conversion give the value False: undefined, NULL, 0, -0, NAN, "".
  • The false value is returned unchanged.
  • All other values \u200b\u200bas a result of the conversion give True value.

Convert to string

The String () feature converts values \u200b\u200bto the following rules:

  • For all values, other than NULL and undefined, the TOSTRING () method is automatically called and the string representation of the value is returned.
  • For NULL value, the "NULL" row is returned.
  • For undefined value, the "undefined" row is returned.

Converting simple types to objects

To convert ordinary values \u200b\u200bto objects used boolean (), Number (), String ():

VAR Onum \u003d New Number (3); var ostr \u003d new string ("1.2"); Var Obool \u003d New Boolean (True); Alert (Typeof Onum); // "Object" Alert (Typeof OSTR); // "Object" Alert (Typeof Obool); // "Object"

Convert objects to simple values

All objects inherit two methods of conversion: Tostring () and Valueof ().

Tostring () method Returns the string representation of the object. By default, he does not return anything interesting:

Alert ((x: 1) .tostring ()); // ""

Some types have more specialized versions of the TOSTRING () method. For example, the TOSTRING () method in the array converts all its elements into the string and then combines them into one line, inserting commas between them:

Alert (.tostring ()); // "1,2,3"

The task of the ValueOF () method is not defined as clearly: it is assumed that it should convert an object into an indicative of its simple value if such a value exists. Objects are inherently composite values, and most objects cannot be represented as a single simple value, so by default the ValueOF () method returns not a simple value, but a link to it:

Alert (Typeof (X: 2) .Valueof ()); // "Object"

When the object is converted to the string, the JavaScript interpreter performs the following actions:

  • If the object has a TOSTRING () method, the interpreter calls it. If it returns a simple value, the interpreter converts the value to the string (if it is not a string) and returns the result of the conversion.
  • If the object does not have the TOSTRING () method or this method does not return a simple value, the interpreter checks the presence of the ValueOF () method. If this method is defined, the interpreter calls it. If it returns a simple value, the interpreter converts this value to the string (if it is not a string) and returns the result of the conversion.

When converting an object to the number, the interpreter performs the same actions, but the first is trying to apply the ValueOF method ():

  • If the object has a ValueOF () method, returning a simple value, the interpreter converts (if necessary) a value in the number and returns the result.
  • If the object does not have the ValueOF () method or this method does not return a simple value, the interpreter checks the presence of the TOSTRING () method. If the object has a TOSTRING () method, returning a simple value, the interpreter performs the conversion and returns the resulting value.
  • Otherwise, the interpreter concludes that neither the Tostring () nor Valueof () does not allow you to get a simple value and excites TypeError error.

Tostring () and ValueOF () methods are available for reading and writing, so they can be overridden and explicitly indicate that it will be returned when converting:

Var OBJ \u003d (); obj.tostring \u003d function () (RETURN "OBJECT";); Alert ("This" + OBJ); // "This is the object"

Last updated: 1.11.2015

Often there is a need to convert some data to others. For example:

Var number1 \u003d "46"; var NUMBER2 \u003d "4"; VAR Result \u003d Number1 + Number2; Console.log (Result); // 464.

Both variables represent strings, or rather string representations of numbers. And in the end we will receive no number 50, but a string 464. But it would be nice if they could also be folded, subtract, in general, working as with ordinary numbers.

In this case, we can use conversion operations. To convert string to the number applies function parseint ():

Var number1 \u003d "46"; var NUMBER2 \u003d "4"; Var Result \u003d Parseint (Number1) + Parseint (NUMBER2); Console.log (Result); // fifty

Function is used to convert strings to fractional numbers parseFloat ():

Var number1 \u003d "46.07"; var NUMBER2 \u003d "4.98"; VAR Result \u003d Parsefloat (Number1) + ParseFloat (Number2); Console.log (Result); //51.05

In this case, the string may 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 perform the transformation:

Var num1 \u003d "123hello"; var Num2 \u003d Parseint (Num1); Console.log (Num2); // 123.

If the method cannot be converted, it returns the Nan value (not a number), which indicates that the string does not represent the number and cannot be transformed.

Using a special function iSNAN () You can check if the number is submitted. If the string is not a number, then the function returns True if this is the number - then FALSE:

Var num1 \u003d "javascript"; var num2 \u003d "22"; Var Result \u003d Isnan (Num1); Console.log (Result); // True - Num1 is not a number result \u003d isnan (Num2); Console.log (Result); // False - Num2 is the number

Above, we considered the translation of strings in the number in the decimal system. However, we can translate numbers to any system. By default, the JavaScript interpreter guess itself, among which calculus system we want to convert a string (as a rule, a decimal system is selected). But we can clearly indicate that we want to convert a row to a number in a specific system. For example, converting a binary system:

Var num1 \u003d "110"; var num2 \u003d Parseint (Num1, 2); Console.log (Num2); // 6.

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

Now write a small program in which we use variable operations:

Javascript.

Using the Prompt () function, the browser displays a dialog box with a proposal to enter a certain value. The second argument in this function indicates the value that will be used by default.

However, the Prompt () function returns the string. Therefore, we need to convert this line to perform operations with it.

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

The next message will then be displayed and to enter the percentage. And at the end the program will receive data, converts them to numbers and calculates.

Hello, dear readers. Today I will write, as transformed into javascript. Row to the number. This is done using the Number function, now I will show its use on the example.
Also, I propose to watch the video version of this article:

A little about data types

As you know, JavaScript has a numeric and string data type. Let's try to create two variables in which you save the number, and then we will withdraw the result on the screen.

Var a \u003d 5; var b \u003d 12; Document.Write (A + B);

What will be the result? 17, which brought us browser. So, these are numeric data, so the browser has successfully folded them. And now let's create the other two variables in which we put the same values, but in quotes. I remind you all the rows in JavaScript are written in quotes.

Var c \u003d "5"; var d \u003d "12"; Document.Write ("
"+ C + D);

Now the browser considers our data to lines and if we fold them, then two lines will simply be folded and we will get 512 that there is no correct result if there were numbers, but it is right if you put together two lines.

How to convert to JavaScript row to the number?

Here everything is simple, create the next two variables, in which we write the same value that the variable C and D is set, but by passing them through the Number method:

Var E \u003d Number (C); var F \u003d Number (D); Document.Write (E + F);

If you now try to output the result from this addition on the screen, then 17. All because our method has successfully worked and transformed a row to the number. I want to note that if you write like this:

Document.Write ("
"+ E + F);

Then 512 will be displayed on the screen, because when adding strings and numbers ALWAYS The result is converted to the string. If you want to add a row transfer and, while maintaining the correct result, you can write everything in two rows or in the same way:

Document.Write ("
"+ (E + F));

If you take numbers in brackets, they will not be converted into strings and successfully retain their properties. Here is such a short article today. I hope JavaScript has become a little clearer for you.

In JavaScript there are 2 built-in functions to convert rows in numbers: Parsefloat () and Parseint ().

pARSEFLOAT () takes the argument a string that must be brought to a numerical type, and returns the number of type float. The number should be contained at the beginning of the line. If after a number in the line there are still some characters, then they cut off. The fractional part of the number should be recorded through the point (the comma is not perceived as a separator). In case ParsEfloat () cannot convert a string, it returns Nan.

Also, the function can handle the "Num N multiplied by 10 to the degree x", which in the programming it is customary to record through the letter E, for example: 0.5E6 or 0.5E + 6. The degree may also be negative: 0.5E-6, which is 0.5 * 10 ^ -6 or 0.5 / 1000000.

ParseFloat ("" 3.78kg ") // 3.78 PARSEFLOAT (" "KG33" ") // Nan Parsefloat (" "0004.111" ") // 4.111 ParseFloat (" 0x66 "") // 0 ParseFloat ("". 5 "") // 0.5 PARSEFLOAT ("" -. 5 "") // -0.5 ParseFloat ("" 0.5E6 "") // 500000 PARSEFLOAT ("0.03E + 2" ") // 3 ParseFloat (" "3E-4" ") // 0.0003 PARSEFLOAT (" "- 3E-4" ") // -0.0003

The PARSEINT (STRING [, RADIX]) feature takes the string as the first argument, analyzes it and returns an integer (type Integer). The function is trying to analyze the number system in which the number is recorded in the source line (for example, decimal, octal or hexadecimal - but not only these). Also, the number system can be specified explicitly by passing it by the second RADIX parameter. The RADIX parameter can take any number from 2 to 36 (in systems above the 10th, the letters of the English alphabet are used, from A to Z).

Numbers type 1.5E6 The function does not handle as ParsEfloat ().

Please read the examples below so as not to put on the pitfalls, are harnessed in the operation of the Parseint () function.

Parseint ("" 25 "") // 25 PARSEINT ("" - 25 "") // -25 PARSEINT ("" 45.12 "") // 45 PARSEINT ("045" ", 10) // 45 Parseint ( "70", 8) // 56 (70 in the octal system it is 56 in decimal) Parseint ("" 070 ") // 56 (important !!! Zero will first force the function to analyze the string as an octal number) Parseint (" "88" ", 8) // Nan (in the octal system no digit 8) Parseint (" "A1") // Nan (important !!! The default function does not perceive the number as 16-rich, if not adding at the beginning Rows 0x) PARSEINT ("" A1 "", 16) // 161 (here is clearly indicated by the number system) PARSEINT ("0xa1") // 161 (the correct 16-riche number format, you can not specify the second parameter) Parseint ( "" 099 "") // 0 (important !!! The number is perceived as octal, but containing invalid characters) Parseint ("" 0.5E6 ") // 0 (important !!! not working as ParseFloat) Parseint (" " ZZ "", 36) // 1295 PARSEINT ("" - FF "") // Nan Parseint ("" - FF "", 16) // -255

If you handle data from a text field that enters the user, always use Parseint () along with the second Radix parameter, it will protect your code from unexpected results.