Javascript number to lowercase conversion. Converting data types in JavaScript. Converting to Boolean Values

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

console.log(sum(1, 2)); // 3 (everything is ok here) console.log(sum(1, "2")); // 12 (not very good here)

As can be seen from the example, the function sum behaves incorrectly if a non-number is passed as at least one of its arguments. 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 adjust 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(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

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

Type casting

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

Converting a string to a number

Sometimes the programmer himself can change the type of a variable by applying certain operations to it. For example, incrementing or decrementing operations on a string will reduce it to a number.

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

It is worth noting that there is no 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 for this task in js parseInt And parseFloat. As the first argument, they take the string that needs to be converted to a number, and as an optional second argument, they take the base of the number system in which the number is written in the string passed as the first argument. If the second argument is not specified, then it will be assumed that the line 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 fraction.

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 scientific notation.

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 that the function parseInt And parseFloat is taken 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

In JavaScript, a value of any type can be cast to a string. It was already mentioned above that when a string is concatenated with a number, the number is reduced to the string, and only then does concatenation occur. This will happen with a value of any 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(typeof str); // string console.log(str); // str = .toString(); console.log(typeof str); // string console.log(str); // 1,2,3

Numeric conversion

Conversion to a number occurs when performing mathematical operations and when performing a comparison operation with type casting (==, !=), and the value false and empty array are converted to value 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 not 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!

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 appear at the beginning of the line. If there are any other characters in the line after the number, they are cut off. The fractional part of a number must be written separated by a dot (a comma is not perceived as a separator). If parseFloat() cannot convert the string, it returns NaN.

The function can also process “the number n multiplied by 10 to the x power,” which in programming is usually written with 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 (type integer). The function attempts to analyze the number system in which the number in the source string is written (for example, decimal, octal or hexadecimal - but not only these). You can also specify the number system explicitly by passing it as the second parameter radix. The radix parameter can take any number from 2 to 36 (in systems higher than 10, letters of the English alphabet are used, from A to Z).

The function does not handle numbers like 1.5e6 like parseFloat() .

Please read the examples below so as not to stumble upon the pitfalls hidden 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 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 the octal system) parseInt(""a1"") // NaN (IMPORTANT!!! The default function does not treat the number as hexadecimal if it is not added at the beginning lines 0x) parseInt(""a1"",16) // 161 (the number system is explicitly specified here) parseInt(""0xa1"") // 161 (correct hexadecimal number format, you don't have to specify the second parameter) 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 process data from text field, which the user enters, always use parseInt() along with a second radix parameter, this will protect your code from unexpected results.

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:

  1. 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.
  2. 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.
  3. 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 was 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

DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung InternetNode.js
parseIntChrome 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
Parses leading-zero strings are decimal, not octalChrome 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

Hello dear readers. Today I will write how it is converted into javascript string to number. This is done using the Number function, now I will show its use with an example.
I also suggest watching the video version of this article:

A little about data types

As you know, javascript has numeric and string data types. Let's try to create two variables in which we will store the numbers, and then display the result on the screen.

Var a = 5; var b = 12; document.write(a + b);

What will be the result? 17, which is what the browser showed us. So this is numeric data, so the browser has successfully added it up. Now let's create two other variables, in which we will put the same values, but in quotes. Let me remind you that all lines in javascript are written in quotes.

Var c = "5"; var d = "12"; document.write("
" + c + d);

Now the browser considers our data to be strings and if we add them, then two lines will simply be added and we will get 512, which is not the correct result if numbers were added, but is correct if we put two lines together.

How to convert a string to a number in javascript?

Everything is simple here, let’s create the next two variables, into which we will write the same value that is specified by the variables c and d , but passing them through the Number method:

Var e = Number(c); var f = Number(d); document.write(e + f);

If you now try to display the result of this addition on the screen, it will display 17. This is because our method successfully worked and converted the string into a number. I would like to point out that if you write it 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 a string. If you want to add a line break and still keep the correct result, you can write everything on two lines or one like this:

Document.write("
" + (e + f));

If you put numbers in brackets, they will not be converted to strings and will successfully retain their properties. This is my short article today. I hope javascript has become a little clearer for you.

Choice