Several methods of converting numbers to strings in JS

Source: Internet
Author: User

A. To convert a number to a string, simply add an empty string to it:

var n = 100;
var n_as_string = n + "";

B. To make a number more explicitly converted to a string, you can use the string () function:

var string_value = string (number);

C. Use the ToString () method:

String_value = Number.tostring ();

The Number object (the basic numbers are converted to the numeric object so that this method can be called) The ToString () method has an optional parameter that specifies the cardinality of the transformation. If you do not specify this parameter, the conversion will be based on a base of 10. However, you can also convert numbers according to other cardinality (numbers from 2 to 36).

var n = 17;
binary_string = n.tostring (2); Evaluates to "10001"
Octal_string = "0" + n.tostring (8); Evaluates to "021"
hex_string = "0x" + n.tostring (16); Evaluates to "0x11"

The D. ToFixed () method converts a number to a string and displays the specified number of digits after the decimal point. It does not use exponential notation.

var n = 123456.789;
n.tofixed (0); "123457"
N.tofixed (1); "123456.79"

E. toexponential () converts a number to a string using exponential notation, preceded by a 1-digit number, and a specific number of digits after the decimal point.

var n = 123456.789;
N.toexponential (1); "1.2e+5"
N.toexponential (3); "1.235e+5"

F. toprecision () displays a number using the specified number of significant digits, and uses exponential notation if the meaningful number of digits is not sufficient to display the entire integer portion of the number.

var n = 123456.789;
N.toprecision (4); "1.235e+5"
N.toprecision (7); "123456.8"

Several methods of converting numbers to strings in JS

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.