LEARNING JAVASCRIPT - Trang 255

x

.

toPrecision

(

2

);

// "1.0e+3"

x

.

toPrecision

(

1

);

// "1e+3"

x

=

15.335

;

x

.

toPrecision

(

6

);

// "15.3350"

x

.

toPrecision

(

5

);

// "15.335"

x

.

toPrecision

(

4

);

// "15.34"

x

.

toPrecision

(

3

);

// "15.3"

x

.

toPrecision

(

2

);

// "15"

x

.

toPrecision

(

1

);

// "2e+1"

Output is rounded, and will always have the specified number of digits of precision. If

necessary, output will be in exponential notation.

Different Bases

If you want to display numbers in a different base (such as binary, octal, or hexadeci‐

mal),

Number.prototype.toString

takes an argument specifying the base (in the

range 2 to 36):

const

x

=

12

;

x

.

toString

();

// "12" (base 10)

x

.

toString

(

10

);

// "12" (base 10)

x

.

toString

(

16

);

// "c" (hexadecimal)

x

.

toString

(

8

);

// "14" (octal)

x

.

toString

(

2

);

// "1100" (binary)

Advanced Number Formatting

If you’re displaying a lot of numbers in your application, your needs may quickly sur‐

pass what the built-in JavaScript methods provide. Common needs are:

• Thousands separators
• Displaying negative numbers differently (for example, with parentheses)
• Engineering notation (similar to exponential notation)
• SI prefixes (milli-, micro-, kilo-, mega-, etc.)

Providing this functionality can be educational if you’re looking for a reader’s exer‐

cise. If you’re not, I recommend the

Numeral.js library

, which provides all of this

functionality and more.

Constants

The usual important constants are available as properties of the

Math

object:

// fundamental constants

Math

.

E

// the root of the natural logarithm: ~2.718

Math

.

PI

// the ratio of a circle's circumference to its diameter: ~3.142

Constants | 231

Liên Kết Chia Sẽ

** Đây là liên kết chia sẻ bới cộng đồng người dùng, chúng tôi không chịu trách nhiệm gì về nội dung của các thông tin này. Nếu có liên kết nào không phù hợp xin hãy báo cho admin.