Current location - Plastic Surgery and Aesthetics Network - Plastic surgery and beauty - How to convert javascript strings to numeric types
How to convert javascript strings to numeric types
There are three main methods.

Conversion function, forced type conversion, weak type conversion using js variables.

Use the functions parseInt () and parseFloat () to convert values to integers and the latter to floating-point numbers. Only by calling these methods on a numeric String of type String can these two functions run correctly; For other types, NaN (non-numeric) is returned.

parse int(" 1234 blue "); ? //Results? 1234

parse int(" 0xA "); ? //Results? 10

parse int(" 22.5 "); ? //Results? 22

parse int(" blue "); ? //Results? Disc scone

parse float(" 1234 blue "); ? //Results? 1234.0

parse float(" 0xA "); ? //Results? Disc scone

parse float(" 22.5 "); ? //Results? 22.5

parse float(" 22 . 34 . 5 "); ? //Results? 22.342. Forced type conversion, number(value)- converts a given value into a number (which can be an integer or a floating-point number);

Number (fake)? //Results? 0

Numbers (true)? //Results? 1

Quantity (undefined)? //Results? Disc scone

Number (empty)? //Results? 0

No. (? "5.5?" )? //Results? 5.5

No. (? "56?" )? //Results? Fifty-six

No. (? "5.6.7?" )? //Results? Disc scone

No. (new? Object())? //Results? Disc scone

No (100)? //Results? 1003. Using js variables for weak type conversion

var? str=? '0 12.345?' ;

var? x? =? str-0;

x? =? x * 1; ? //x performs arithmetic operation on the number type to realize the type conversion from string to number, but this method is not recommended.