How to convert a string to a number in JavaScript

Source: Internet
Author: User
Tags numeric

This article describes the method of digital spin string and string-spin in JavaScript

The simplest way to spin a digital string in JavaScript is to:

var num = 123;

var string = num + "";

That is, add a null character after the number. What about the simplest method of string-spin?

Strings can only be additive (stitching)

string addition (stitching) is very common, but the string for subtraction, multiplication, division?

This seems to be difficult to define, in fact, there is no subtraction, multiplication, division operation of Strings.

But JavaScript is a dynamic language, and if you take these three actions with two strings, he will try to turn them into numbers and then do the appropriate action. For example:

Alert ("45"-"32"); 13

Alert ("5" * "6"); 30

Alert ("12"/"3"); 4

But this conversion operation is not much like parseint and parsefloat, and it is similar to number, for example:

Alert ("123a"-"2BC"); NaN

Alert (parseint ("123a")-parseint ("2BC")); 121

Alert (Number ("123a")-Number ("2BC")); NaN

That is, this conversion, like number, converts the impure numeric string to Nan, indicating that it is a non-numeric.

And parseint, Parsefloat takes out the string to take out the front can be expressed as a number of parts, and ignore the following can not be expressed as a number of parts.

Related Article

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.