JavaScript conversion of the number in the string. JavaScript: Data Type Conversion

JavaScript is an inepiest language (more precisely, weakly typed or dynamically typed). This means that we should not specify the type of variable when declared it. The ineposis gives JavaScript flexibility and simplicity, preferred for the scripting language (although these features get the price of the lack of rigor, important for long and more complex programs that are often written on more stringent languages, such as C or Java). An important feature of flexible work with data types in JavaScript is the automatic data transformations performed by the interpreter. For example, if the document.write () method is transmitted, JavaScript automatically converts it to an equivalent string representation. Similarly, checking the string value in the IF instruction condition, JavaScript automatically converts this string to a logical value - in FALSE, if the string is empty, and in True otherwise.

The main rule is that when the value of one type occurs in the context, where the value of some other type is required, JavaScript automatically tries to convert the value in the desired manner. Therefore, for example, in the context, which assumes a logical variable, the number is converted to a logical value.

The object in the string context is converted to the string. Mounting in the numeric context of JavaScript is trying to convert to the number.

Conversion "Elementary Type Object"
For example, in a logical context, all objects below are converted to True:

New Boolean (FALSE) // Internal value equals false, but the object
// Converted to True
NEW NUMBER (0)
New String (")
NEW Array ()

The transformation of objects in the number begins with the call of the ValueOf () method of this object. Most objects inherit standard method Valueof () class Object, which simply returns the object itself. Since the standard ValueOF () method does not return the elementary value, JavaScript then tries to convert the object to a number by calling its TOSTRING () method and converting the resulting string. For arrays, this leads to interesting results. Recall that the TOSTRING () method converts the elements of the array into the string, and then returns the result of the concatenation of these rows with commas between them. Consequently, an array without elements is converted into an empty string that is converted to 0! In addition, if the array consists of one element, the number n, the array is converted into a string representation of this number, which is then converted back to the number N.

If an array contains more than one element, or if its single element is not a number, the array is converted to NaN. In JavaScript, the context is not always determined unequivocally! Operator + and comparison operators (and\u003e \u003d) work both with numbers and strings, so when the object is used with one of these operators, it is unclear what it must be transformed into a number or in a string. In most cases, JavaScript first tries to convert an object by calling the ValueOF () method. If this method returns the elementary value (usually the number), this value is used. However, often Valueof () simply returns an object without conversion; In this case, JavaScript then tries to convert an object to the string using the TOSTRING () method call. There is only one exception to this conversion rule: when the Date object is used with the + operator, the conversion is performed using the Tostring () method. The existence of this exception is due to the fact that the Date has both the TOSTRING () method and the ValueOF () method. When using the DATE with the operator + almost always required a string concatenation. But when Date is involved in comparison operations, it is almost always necessary to perform a numerical comparison in order to determine which of the two points of time was preceded by another.

Most objects or do not have the ValueOF method (), or this method does not return useful results.

When the operator + is used to the object, the string concatenation usually takes place, and not addition. When the comparison operator is applied to the object, a string comparison is usually performed, not a numeric.

Object defining special method Valueof () may behave differently. By defining the ValueOF () method, returning the number, you can apply arithmetic and other statements to your object, but the addition of your object will be performed not as expected: the Tostring () method is no longer called and a string representation of the number returned by the method is involved in concatenation Valueof ().

Finally, remember that the ValueOF () method is not called Tonumber (), strictly speaking, its task is to convert an object into a meaningful elementary value, so some objects may have Valueof () methods that return rows.

Explicit conversion types
Java-Script does not define the transformation operator as in C, C ++ and Java languages, but provides similar means. In JavaScript 1.1 (and in ECMA-262) Number (), Boolean (), String () and Object () can be called not only as designers, but also as functions. Being caused in this way, these functions are trying to convert their
Arguments in the appropriate type. For example, you can convert any x value to the string using String (x) and any value of Y to an object using Object (Y).

There are several more techniques that can be useful for performing explicit type transformations. In order to convert a value to a string, make it a concatenation with an empty string:

Var x_as_string \u003d x + "";

To convert a value to a number, deduct zero from it:

VAR X_AS_NUMBER \u003d X - 0;

It is possible to transform any value to a logical value using the operator!, Twice applied:

Var x_as_boolean \u003d !! x;

Due to JavaScript tendency to automatically convert data to the required in this moment Type, explicit conversions are usually not required. However, occasionally they are useful, and can be applied to make the program clearer and more accurate.

Transformation of numbers in the string
The transformation of numbers in the string is performed in JavaScript, possibly more often than others. Although it usually happens automatically, there are several useful ways to explicitly transform this kind. Two we have already seen:

Var String_Value \u003d String (Number); // Using the String Designer ()
// as a function
Var String_Value \u003d Number + ""; // Concatenation with an empty string

Another opportunity provides the method toostring ():

String_Value \u003d Number.tostring ();

The Tostring () method of the Number object (elemental numeric values \u200b\u200bare converted to Number objects, so you can call this method) accepts an optional argument that sets the base of the number system to which the conversion will be performed. If the argument is not specified, the transformation is performed by base 10. But you can convert numbers with other bases (between 2 and 36). For example:

Var n \u003d 17;
binary_string \u003d n.tostring (2); // Equally "10001"
Octal_String \u003d "0" + n.tostring (8); // Equally "021"
hex_string \u003d "0x" + n.tostring (16); // Equally "0x11"

Lack of JavaScript versions to version 1.5 consists in absence standard fashionallowing you to specify the number of decimal signs in the row resulting from the transformation of the number, or require the use of exponential notation. This may complicate the display of numbers having traditional formats, such as cash values.

ECMAScript V3 and JavaScript 1.5 bypass this obstacle by adding three new conversion method into the line to the Number class. The Tofixed () method converts the number to the string and displays the specified number of numbers after the decimal point without using exponential notation. The toexponential () method converts the number to the string, recording it in exponential notation with one digit before the decimal point and the specified number of numbers after it. The TopRecision () method displays a number using the specified number of significant digits. If such a number of significant digits is not enough to output a whole part of the number, it is recorded in exponential notation. Please note that all three methods correctly rounded the resulting line figures. Look at the following examples:

Var n \u003d 123456.789;
n.tofixed (0); // "123457"
n.tofixed (2); // "123456.79"
N.ToExponential (1); // "1.2E + 5"
N.ToExponential (3); // "1.235E + 5"
N.TOPRECISION (4); // "1.235E + 5"
N.TOPRECISION (7); // "123456.8"

Row conversion in numbers
We have seen that in the numerical context of the line representing numbers are automatically transformed into real numbers. As shown above, this conversion can be explicitly:

VAR Number \u003d Number (String_Value);
VAR Number \u003d String_Value - 0;

Such a transformation is inconvenient due to its excessive rigor. It works only with decimal numbersAnd although the conversion allows leading and closing spaces, it does not allow any non-flagged characters after the number in the line. For more flexible transformations, you can use PARSEINT () and PARSEFLOAT () functions. These functions are transformed and returned by any number present at the beginning of the line, ignoring any closing non-numeric characters. The PARSEINT () function processes only integer, and ParseFloat () is both integers and floating point numbers. If the string begins with "0x" or "0x", Parseint () interprets it as a hexadecimal number. For example:

PARSEINT ("3 Blind MICE"); // Returns 3.
ParseFloat ("3.14 Meters"); // Returns 3.14.
Parseint ("12.34"); // Returns 12.
PARSEINT ("0xFF"); // Returns 255.

The PARSEINT () function may have a second argument indicating the base of the number of the processed number. Valid values - from 2 to 36. For example:

Parseint ("11", 2); // Returns 3 (1 * 2 + 1)
PARSEINT ("FF", 16); // Returns 255 (15 * 16 + 15)
Parseint ("zz", 36); // Returns 1295 (35 * 36 + 35)
Parseint ("077", 8); // Returns 63 (7 * 8 + 7)
Parseint ("077", 10); // Returns 77 (7 * 10 + 7)

If PARSEINT () and PARSEFLOAT () cannot convert the specified string to the number, they return Nan.

Parseint ("Eleven"); // Returns Nan.
ParseFloat ("$ 72.47"); // Returns Nan.

There is no difference in what type of variable is used in expression. If the expression is mathematical, all of its variables will automatically be interpreted as numeric. If lines are processed, then all the "participants" of expressions are considered as lines. However, the conversion task to JavaScript "row to the number" exists in a much broader context.

JavaScript methods of rows conversion in numbers

Arsenal methods for converting strings in numbers is not large, but sufficient in all simple cases. Here JavaScript (for beginners especially) is the path from from simple to complex in practical examples.

The example describes four different lines. In the first block of output type each variable function Typeof is defined as String. Then each line is very simply converted to the number. In the second output block, changes in variables after the transformation are visible, their type has become a number. The JavaScript Parasefloat conversion example is especially indicative: it was "12E + 3", it became "12000".

Changes when converting a string to a number can be significant! But only the first characters are important: they should be digital. If there is not a single digital symbol, the result will be Nan.

The reverse transformation of the string "has become" by the number is not always the same string. This moment can be used to verify the correctness of entering numerical information.

Conventional transformation methods

There are integers and there are fractional, respectively, JavaScript row to the number converts by:

  • parseint;
  • parsefloat.

The general case is implemented by using a string in a simple mathematical expression.

It is enough to put in front of the symbol string "+" and if there is a number in it, the result of the expression will be the number. The value of the variable may change, but the type will always change: Typeof will show Number, not String. It is important to understand that the use of a transformed variable in line expression can show a completely different result.

JavaScript for beginners in this context is extremely simple. It is more difficult to understand the work of an integer conversion by the PasRseint method, since it works in the machine decimal system Number, but can interpret the string as an octal or hexadecimal. In this case, this circumstance does not always depend on the second parameter, which indicates the number system.

JavaScript row to the number always turns, but if there is no digital symbol in the row at the beginning of the line, then the result will be NaN.

It is necessary to have ideas about the number systems, about the methods of recording hexadecimal (the number begins with "0x") and octal numbers (the number begins with "0").

To understand the nuances of the JavaScript method ParsEfloat, it is enough to have an idea of \u200b\u200bwhat mathematical record is a real number.

Conversion

JavaScript is a browser language, because it is more other languages \u200b\u200bcritical of the symbols outside the main set of the Latin alphabet and numbers. Sort - Survived operation. But it does not always make sense to send data to the server for sorting purposes, easier and more practical to work in place in the browser.

To solve such a task, you can convert string symbols into their numeric codes or assign an ordered sequence of numbers in their numeric codes or digit and digit. The charcodeat () method applied to the string assigns a numeric value 98 of the IB variable, that is, the letter code "B". Considering that the value of the code of the letter "A" is 97, you can get the numbers of all the letters of the Latin alphabet in ascending order on line and uppercase sets. Similar to the letters of the Russian alphabet.

Own sorting variant through numbers allows you to form the desired sets of characters. It is possible, for example, to "intercept" Cyrillic and Latin and mix them in order to leave only excellent writing letters, add to the sets of tabs and spaces.

Formation of a unique number of string

If the letter code "A" is 97, then the difference between the letter and number 97 will give a unique number of the letter in the alphabet. Summarizing unique numbers for each line symbol, it is difficult to get a unique number of this string.

If each position of the letter in the string is assigned weight, for example, position:

  • 0 weight 1;
  • 1 weight 10;
  • 2 weight 100;

it is multiplying the unique number of each character of the string on the weight of the position in which it is detected, and by summing all the numbers you can get a unique number and use it as an unambiguous correspondence in the original line.

Such a row conversion is a reversible, that is, by the number you can always get the source line. Such a transformation is beneficial, because with a number you can make any operation safely in the context of encoding, Cyrillic and other local features of the site page, field of application, visitor countries.

"Growing" Site Page Selectors

It often occurs the task of creating selectors on the site pages, the values \u200b\u200bof which cannot be specified in advance, but over time they are complemented. In the very first application, an empty selector is available to the first visitor to enter information.

Each new entry of the information lines in the selector (by any visitor) is transformed into the number, which, together with the original, is sent to the storage server. When a new work session begins or a new visitor comes, the selector is no longer empty. The download page comes to the browser with a non-empty selector.

With each new selector value, only once it goes to the storage server and only once it is assigned a unique digital code.

To solve this task, the JavaScript method cannot be used to use a row. The usual PARSEINT and PARSEFLOAT methods are designed for other use, but you can come up with an algorithm for the unambiguous conversion of the string in the number, and not necessarily reversible. It is enough that the conversion algorithm algorithm will not be repeated in different sets of characters in the line.

Traffic Optimization and Analytics

When forming a page, the developer uses significant amounts of information. Provide a visitor to enter information - good way To lower the site rating due to its weak functionality and disappoint the visitor.

Assigning an event handler in the form of a JavaScript Function to the actions of the visitor for certain information blocks, you can formulate a filter that will allow the visitor to accurately put a goal, find necessary information, get the desired solution.

The transformation of lowercase information here may be an arbitrarily capacious in part of the line and very small in the number. In other words, the conversion of JavaScript row to the number of developer performs according to its algorithm. The visitor manipulates understandable information, and the server has a minimum amount of data - a number.

The dynamics of many numbers on all visitors in the context of exactly known information allows another JavaScript Function (not handler), called by server response through the AJAX mechanism, promptly real-time to give all visitors the necessary information at the same time. So the system works.

This option for converting JavaScript row is very in demand in the development of online games, interactive conferences, transfer instant messages etc.

Tool use of transformations

JavaScript and CSS in the context of processing numeric information allow you to manage the page display without server participation. CSS rules are built as substring, recursively. Usually the parameter is the number followed by several letters (for example, "PX", "PT", "EM", ...). The parameter is a substress in the rule, and the rule enters a substrol in the style of a class or identifier.

Recursion JavaScript.Strete. The structure ... goes to the desired number, converts from the string to the number, changes it and writes back to the desired location. The rule is changing "machine". It is simple and convenient, no server participation.

There are two main ways to convert string to JavaScript. One way is to analyze it, and another way - change its type to the number. All tricks in other responses (for example, unary plus) imply implicit coercion like a string to the number. You can also do the same with the Number function.

Syntactic

Var Parsed \u003d Parseint ("97", 10);

pARSEINT and PARSEFLOAT are two functions used to parsing rows into numbers. Syntax analysis will stop silently if it falls into a symbol that it does not recognize that it can be useful for syntactic analysis of strings, for example "92px", but it is also somewhat dangerous because it will not give you no error with a bad entry, instead you "Return Nan if the string does not start with the number. The gap at the beginning of the line is ignored. Here is an example of what he does something differently, what you need, and does not indicate that something went wrong:

Var widgetssold \u003d Parseint ("97,800", 10); // Widgetssold IS NOW 97

Good practice always indicate as a second argument. In old browsers, if the string began with 0, it would be interpreted as octal, if it were not specified by the value of Radix, which attracted many people by surprise. Behavior for hexadecimal launch starts if the string begins with 0x if the Radix value is not specified. 0xFF. The standard actually has changed using ECMAScript 5, so modern browsers No longer run octal when the host is indicated if the Radix value is not specified. Parseint understands radics to base 36, and in this case both the upper and lowercase letters are processed as equivalent.

String type change by number

All other tricks mentioned above that do not use Parseint, imply implicit coercion of the string to the number. I prefer to do it clearly

Var Cast \u003d Number ("97");

This is different from analysis methods (although it still ignores spaces). It is strict: if it does not understand the entire line than the Nan returns, so you cannot use it for strings of type 97px. Since you need a primitive number, not the Number wrapper object, make sure that you do not set the new before the Number function.

Obviously, the conversion to the number gives you a value that can be Float, and not a whole number, so if you want an integer, you need to change it. There are several ways to do it:

Var rounded \u003d math.floor (Number ("97.654")); // Other options Are Math.ceil, Math.round Var Fixed \u003d Number ("97.654"). Tofixed (0); // Rounded Rather Than Truncated Var BitWised \u003d Number ("97.654") | 0; // Do Not Use for Large Numbers

Any bitter operator (here I am a blessing or, but you can also make a double negation, as in an earlier answer or bit shift) converts the value to a 32-bit integer, and most of them are converted to a signed integer. Note that this Will not need for large integers. If an integer can be represented in 32 bits, it will be completed.

~~ "3000000000.654" \u003d\u003d\u003d -1294967296 // THIS IS THE SAME AS NUMBER ("3000000000.654") | 0 "3000000000.654" \u003e\u003e\u003e 0 \u003d\u003d\u003d 3000000000 // unsigned right shift gives you an extra bit "300000000000.654"\u003e \u003e\u003e 0 \u003d\u003d\u003d 3647256576 // But Still Fails WITH LARGER NUMBERS

To properly work with large numbers, you must use rounding methods

Math.floor ("3000000000.654") \u003d\u003d\u003d 3000000000 // This Is The Same As Math.floor (Number ("3000000000.654"))

Keep in mind that all these methods understand the exponential notation, therefore 2e2 is 200, and not Nan. In addition, Number understands "infinity", while the methods of analysis do not.

Custom

It is wrong that any of these methods does exactly what you want. For example, I usually need an error that occurs when a syntax analysis failure, and I do not need Infinity support, exhibitors or leading gaps. Depending on your use, sometimes it makes sense to write a user conversion function.

Always check that the output of Number or one of the analysis methods is the number you expect. You will almost certainly want to use ISNAN to make sure that the number is not NaN (usually this is the only way to find out that the syntax analysis failed).

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 processes data from text fieldThat enters the user, always use Parseint () along with the second RADIX parameter, it will protect your code from unexpected results.

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.