JavaScript: Data Type Conversion. JavaScript data type conversion Javascript number to string conversion

💖 Like it? Share the link with your friends

JavaScript has 2 built-in functions for converting strings to numbers: parseFloat() and parseInt() .

parseFloat() takes as an argument a string to be converted to a numeric type and returns a float number. The number must be at the beginning of the line. If there are any other characters after the number in the string, they are cut off. The fractional part of the number must be written through a period (the comma is not perceived as a separator). In case parseFloat() cannot convert the string, then it returns NaN.

Also, the function can process "the number n multiplied by 10 to the power of x", which is usually written in programming through the letter E, for example: 0.5E6 or 0.5E+6. The degree can also be negative: 0.5E-6, which is equal to 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]) function takes a string as its first argument, parses it, and returns an integer (integer type). The function tries to parse the number system in which the number in the source string is written (for example, decimal, octal or hexadecimal - but not only these). Also, the number system can be specified explicitly by passing it as the second parameter to radix. The radix parameter can take any number between 2 and 36 (systems above 10 use the English alphabet, A through Z).

Numbers like 1.5e6 are not handled in the same way as parseFloat() .

Please read the examples below so as not to run into the pitfalls hidden in the work of the parseInt() function.

ParseInt(""25"") // 25 parseInt(""-25"") // -25 parseInt(""45.12"") // 45 parseInt(""045"",10) // 45 parseInt( ""70"",8) // 56 (70 in octal is 56 in decimal) parseInt(""070"") // 56 (IMPORTANT!!! zero first will cause the function to parse the string as an octal number) parseInt(" "88"",8) // NaN (there is no digit 8 in octal system) parseInt(""a1"") // NaN (IMPORTANT!!! The default function does not treat the number as hexadecimal unless you add it at the beginning strings 0x) parseInt(""a1"",16) // 161 (the number system is explicitly specified here) parseInt(""0xa1"") // 161 (correct hexadecimal format, the second parameter can be omitted) parseInt( ""099"") // 0 (IMPORTANT!!! The number is treated as octal but contains invalid characters) parseInt(""0.5e6"") // 0 (IMPORTANT!!! does not work like parseFloat) parseInt("" ZZ"",36) // 1295 parseInt(""-FF"") // NaN parseInt(""-FF"",16) // -255

If you are processing data from a text field that the user enters, always use parseInt() along with the second radix parameter, this will protect your code from unexpected results.

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. Conversion Example JavaScript parseFloat 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 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.

| |

JavaScript divides data into types, which helps you group data and determine what values ​​can be assigned and what operations can be performed.

Although JavaScript converts many values ​​automatically due to type casting, it's best to manually convert data types to achieve the expected results.

This tutorial will teach you how to convert primitive types JavaScript data, including numbers, strings, and booleans.

Implicit conversion

The JavaScript programming language is very good at handling unexpected values. JavaScript doesn't reject unexpected values, it tries to convert. This implicit conversion is also called type coercion.

Some methods automatically convert values ​​to use them. The alert() method takes a string as its parameter, and automatically converts other types to strings. Thus, you can pass a numeric value to this method:

If you run this line, the browser will return a popup with a value of 8.5, which will already be converted to a string.

By using strings consisting of numbers along with mathematical operators, you'll find that JavaScript can handle values ​​by implicitly converting strings to numbers:

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

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

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

Because the + operator has many uses, in this example it treats the values ​​2 and 3 as strings, even though they are expressed as numeric strings. Therefore, it combines the strings "2" and "3" and gets 23, and does not add 2 and 3 and gets 5.

This kind of ambiguity occurs in code and sometimes causes unexpected results, so it's best to explicitly convert data types whenever possible. This will help with code maintenance and error handling.

Converting values ​​to strings

To explicitly convert a value to a string, call the String() or n.toString() method.

Try converting boolean true to string with String().

This will return the string literal "true".

You can also try passing a number to the function:

It will return a string literal:

Now try using String() with a variable. Assign a numeric value to odyssey and use the typeof operator to check the type.

let odyssey = 2001;
console.log(typeof odyssey);
number

On this moment the variable odyssey is assigned the numeric value 2001. The typeof statement confirms that the value is a number.

Now assign the odyssey variable to its equivalent inside the String() function, and then use typeof to make sure the variable's value is successfully converted from a number to a string.

odyssey = String(odyssey); // "2001"
console.log(typeof odyssey);
string

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

The n.toString() function works in a similar way. Replace n with a variable.

let blows = 400;
blows.toString();

The blows variable will contain a string.

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

(1776).toString(); // returns "1776"
(false).toString(); // returns "false"
(100 + 200).toString(); // returns "300"

String() and n.toString() explicitly convert boolean and numeric values ​​to strings.

Converting values ​​to numbers

The Number() method can convert a value to a number. Often there is a need to convert strings consisting of numbers, but sometimes boolean values ​​need to be converted as well.

For example, pass the following string to the Number() method:

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

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

let dalmatians = "101";
number(dalmatians);
101

The string literal "101" has been converted to the number 101.

Strings of spaces or empty strings will be converted to the number 0.

Number(" "); // returns 0
number(""); // returns 0

Keep in mind that strings that do not consist of numbers are converted to NaN, which means Not a Number. This also applies to 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 boolean data, false will be 0 and true will be 1.

Converting values ​​to booleans

To convert numbers or strings to booleans, use the Boolean() method. For example, it helps to determine whether the user is entering data into a text field or not.

Any value that is interpreted as empty, such as the number 0, empty line, undefined, NaN, or null values ​​are 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

Note that the string literal "0" is converted to true because it is not an empty value:

Boolean("0"); // returns true

Converting numbers and strings to booleans allows you to evaluate data in binary system and can be used to control flow in programs.

Conclusion

Now you know how JavaScript converts data types. often, casts cause data to be converted implicitly, which can lead to unexpected values. It is recommended that you explicitly convert data types to ensure that correct work programs.

The parseInt() function parses a string argument and returns an integer of the specified radix (the base in mathematical numeral systems).

The source for this interactive example is stored in a GitHub repository. If you"d like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.

Syntax parseInt(string , radix) Parameters string The value to parse. If this argument is not a string, then it is converted to one using the ToString abstract operation. Leading whitespace in this argument is ignored. radix Optional An integer between 2 and 36 that represents the radix (the base in mathematical numeral systems) of the string . Be careful this does not default to 10 ! The explains in more detail what happens when radix is ​​not provided. return value

An integer parsed from the given string .

If the radix is ​​smaller than 11 , and the first non-whitespace character cannot be converted to a number, NaN is returned.

Description

The parseInt function converts its first argument to a string, parses that string, then returns an integer or NaN .

If not NaN , the return value will be the integer that is the first argument taken as a number in the specified radix . (For example, a radix of 10 converts from a decimal number, 8 converts from octal, 16 from hexadecimal, and so on.)

For radices above 10 , letters of the English alphabet indicate numerals greater than 9 . For example, for hexadecimal numbers (base 16), A through F are used.

If parseInt encounters a character that is not a numeral in the specified radix , it ignores it and all succeeding characters and returns the integer value parsed up to that point. parseInt truncates numbers to integer values. Leading and trailing spaces are allowed.

Because some numbers use the e character in their string representation (e.g. 6.022e23 for 6.022 × 10 23), using parseInt to truncate numbers will produce unexpected results when used on very large or very small numbers. parseInt should not be used as a substitute for Math.floor() .

parseInt understands exactly two signs: + for positive, and - for negative (since ECMAScript 1). It is done as an initial step in the parsing after whitespace is removed. If no signs are found, the algorithm moves to the following step; otherwise, it removes the sign and runs the number-parsing on the rest of the string.

If radix is ​​undefined , 0 , or unspecified, JavaScript assumes the following:

  • If the input string begins with "0x" or "0X" (a zero, followed by lowercase or uppercase X), radix is ​​assumed to be 16 and the rest of the string is parsed as a hexidecimal number.
  • If the input string begins with "0" (a zero), radix is ​​assumed to be 8 (octal) or 10 (decimal). Exactly which radix is ​​chosen is implementation-dependent. ECMAScript 5 clarifies that 10 (decimal) should be used, but not all browsers support this yet. For this reason, always specify a radix when using parseInt .
  • If the input string begins with any other value, the radix is ​​10 (decimal).
  • If the first character cannot be converted to a number, parseInt returns NaN unless the radix is ​​bigger than 10 .

    For arithmetic purposes, the NaN value is not a number in any radix. You can call the isNaN function to determine if the result of parseInt is NaN . If NaN is passed on to arithmetic operations, the operation result will also be NaN .

    To convert a number to its string literal in a particular radix, use thatNumber .toString(radix) .

    Examples Using parseInt

    The following examples all return 15:

    ParseInt("0xF", 16) parseInt("F", 16) parseInt("17", 8) parseInt(021, 8) parseInt("015", 10) // but `parseInt(015, 10)` will return 13 parseInt(15.99, 10) parseInt("15,123", 10) parseInt("FXX123", 16) parseInt("1111", 2) parseInt("15 * 3", 10) parseInt("15e2", 10) parseInt("15px", 10) parseInt("12", 13)

    The following examples all return NaN:

    ParseInt("Hello", 8) // Not a number at all parseInt("546", 2) // Digits other than 0 or 1 are invalid for binary radix

    The following examples all return -15:

    ParseInt("-F", 16) parseInt("-0F", 16) parseInt("-0XF", 16) parseInt(-15.1, 10) parseInt("-17", 8) parseInt("-15", 10) parseInt("-1111", 2) parseInt("-15e1", 10) parseInt("-12", 13)

    The following examples all return 4:

    ParseInt(4.7, 10) parseInt(4.7 * 1e22, 10) // Very large number becomes 4 parseInt(0.00000000000434, 10) // Very small number becomes 4

    The following example returns 224:

    ParseInt("0e0", 16) parseInt("123_456") // 123

    Octal interpretations with no radix

    Although discouraged by ECMAScript 3 and forbidden by ECMAScript 5, many implementations interpret a numeric string beginning with a leading 0 as octal. The following may have an octal result, or it may have a decimal result. Always specify a radix to avoid this unreliable behavior.

    ParseInt("0e0") // 0 parseInt("08") // 0, because "8" is not an octal digit.

    ECMAScript 5 removes octal interpretation

    The ECMAScript 5 specification of the function parseInt no longer allows implementations to treat Strings beginning with a 0 character as octal values. ECMAScript 5 states:

    The parseInt function produces an integer value dictated by interpretation of the contents of the string argument according to the specified radix. Leading white space in string is ignored. If radix is ​​undefined or 0 , it is assumed to be 10 except when the number begins with the character pairs 0x or 0X , in which case a radix of 16 is assumed.

    This differs from ECMAScript 3, which discouraged but allowed octal interpretation.

    Many implementations have not adopted this behavior as of 2013, and because older browsers must be supported, always specify a radix .

    A stricter parse function

    It is sometimes useful to have a stricter way to parse integers.

    Regular expressions can help:

    Function filterInt(value) ( ​​if (/^[-+]?(\d+|Infinity)$/.test(value)) ( return Number(value) ) else ( return NaN ) ) console.log(filterInt("421 ")) // 421 console.log(filterInt("-421")) // -421 console.log(filterInt("+421")) // 421 console.log(filterInt("Infinity")) // Infinity console.log(filterInt("421e+0")) // NaN console.log(filterInt("421hop")) // NaN console.log(filterInt("hop1.61803398875")) // NaN console.log (filterInt("1.61803398875")) // NaN

    Specifications Specification Status Comment
    ECMAScript 1st Edition (ECMA-262) standard initial definition.
    ECMAScript 5.1 (ECMA-262)
    standard
    ECMAScript 2015 (6th Edition, ECMA-262)
    The definition of "parseInt" in that specification.
    standard
    ECMAScript Latest Draft (ECMA-262)
    The definition of "parseInt" in that specification.
    Draft
    Browser compatibility

    The compatibility table on this page is generated from structured data. If you"d like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.

    Update compatibility data on GitHub

    Desktop Mobile Server Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet Node.jsparseInt Parses leading-zero strings are decimal, not octal
    Chrome Full support 1Edge Full support 12Firefox Full support 1IE Full support 3Opera Full support YesSafari Full support YesWebView Android Full support 1Chrome Android Full support 18Firefox Android Full support 4Safari iOS Full support YesSamsung Internet Android Full support 1.0nodejs Full support Yes
    Chrome Full support 23Edge Full support 12Firefox Full support 21IE Full support 9Opera Full support YesSafari Full support 6WebView Android Full support 4.4Chrome Android Full support 25Firefox Android Full support 21Opera Android Full support YesSafari iOS Full support 6Samsung Internet Android Full support Yesnodejs Full support Yes

    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 parseInt() function is used to convert a string to a number:

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

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

    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.

    The isNaN() special function can be used to 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 the 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:

    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 var strSum = prompt("Enter deposit amount", 1000); var strPercent = prompt("Enter interest rate", 10); varsum = parseInt(strSum); var percent = parseInt(strPercent); sum = sum + sum * percent / 100; alert("After the accrual of interest, the amount of the deposit will be: " + sum);

    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.



    tell friends