Three ways to convert a JS string into a number

Source: Internet
Author: User
Tags type casting

The value obtained when JS reads a text box or other form data is a string type, such as two text boxes A and B, if a value of value of 11,b is 9,
Then a.value to be smaller than b.value, because they are all in the form of strings.

There are three main methods of this method:
Conversion function, coercion type conversion, using JS variable weak type conversion.

1. Conversion function:

JS provides two conversion functions for parseint () and parsefloat (). The former converts the value into an integer, which converts the value into a floating-point number. Only these methods are called on the string type, and the two functions work correctly;
The return for the other types is Nan (not a number).

parseint () function
Can parse a string and return an integer.
parseint (string, radix)
Radix is optional. Represents the cardinality of the number to parse. The value is between 2 and 36.
If this argument is omitted or its value is 0, the number is parsed based on 10. If it starts with "0x" or "0X", it will have a base of 16.
If the parameter is less than 2 or greater than 36, parseint () returns NaN.
return value
Returns the parsed number.
If the first character of a string cannot be converted to a number, then parsefloat () returns NaN

If string starts with "0x", parseint () resolves the remainder of the string to a 16-binary integer.
If string starts with 0, an implementation of parseint () is allowed to parse subsequent characters into octal or hexadecimal digits.
If string starts with a number from 1 to 9, parseint () parses it into a decimal integer.

Some examples are as follows:

parseint ("1234blue"); Returns 1234
parseint ("0xA"); Returns 10
parseint ("22.5"); Returns 22
parseint ("Blue"); Returns NaN

The parseint () method also has a base mode that converts binary, octal, hexadecimal, or any other binary string into integers. The base is specified by the second parameter of the parseint () method, as in the following example:

parseint ("AF", 16); Returns 175
parseint ("10", 2); Returns 2
parseint ("10", 8); Returns 8
parseint ("10", 10); Returns 10

If the decimal number contains a leading 0, it is best to use cardinality 10 so that the octal value is not unexpectedly obtained. For example:

parseint ("010"); Returns 10
parseint ("010", 8); Returns 8
parseint ("010", 10); Returns 10

The parsefloat () function resolves a string and returns a floating-point number.
The function specifies whether the first character in a string is a number.
If it is, the string is parsed until the end of the number is reached (and then the number is returned as a number, not as a string).
Parsefloat is a global function and does not belong to any object.
If the first character of the argument string cannot be parsed into a number, parsefloat returns NaN.
You can determine whether the return result of Parsefloat is NaN by calling the IsNaN function.
Note: Spaces at the beginning and end are allowed.

Tip: If you want to parse only the integer part of a number, use the parseint () method.

The Parsefloat () method is similar to how the parseint () method is handled.
Another difference between using the Parsefloat () method is that the string must represent a floating-point number in decimal form, and parsefloat () has no base mode.

The following is an example of using the Parsefloat () method:

Parsefloat ("1234blue"); Returns 1234
Parsefloat ("0xA"); Returns 0
Parsefloat ("22.5"); Returns 22.5
Parsefloat ("22.34.5"); Returns 22.34
Parsefloat ("0908"); Returns 908
Parsefloat ("Blue"); Returns NaN

2. Forcing type conversions

You can also use the coercion type conversion (type casting) to handle the type of the converted value. A specific value can be accessed using a coercion type conversion, even if it is of a different type.
The 3 types of coercion conversions available in ECMAScript are as follows:
Boolean (value)-converts the given value to a Boolean type;
Number (value)-converts the given value to a digit (which can be an integer or a floating point);
String (value)-converts the given value to a string.
Using one of these three functions to convert the value, a new value is created that holds the value converted directly from the original value. This can cause unintended consequences.
The Boolean () function returns True when the value to be converted is a string of at least one character, a non-0 number, or an object (this is discussed in the next section). If the value is an empty string, the number 0, undefined, or null, it returns FALSE.

You can test a Boolean type cast with the following code snippet.

Boolean (""); False–empty string
Boolean ("Hi"); True–non-empty string
Boolean (100); True–non-zero number
Boolean (NULL); False-null
Boolean (0); False-zero
Boolean (New Object ()); True–object

The coercion type conversion of number () is similar to the parseint () and parsefloat () methods, except that it transforms the entire value, not the partial value.
Examples are as follows:
Number (false) 0
Number (TRUE) 1
Number (undefined) NaN
Number (NULL) 0
Number ("5.5") 5.5
Number ("56") 56
Number ("5.6.7") NaN
Number (new Object ()) NaN
Number (100) 100

The last method of forcing a type conversion is string (), which is the simplest example of the following:

var S1 = String (null); "NULL"
var onull = null;
var s2 = onull.tostring (); Won ' t work, causes an error

3. Using JS variable weak type conversion
A small example, a look, you will understand.
var str = ' 012.345 ';
var x = str-0;
x = x * 1;

The above example uses the characteristics of the weak type JS, only the arithmetic operation, the implementation of the string to the number of the type conversion, but this method is not recommended

Three ways to convert a JS string into a number

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.