document.write("The price of " + products[0].title + " is $" + products[0].price.toPrecision(5));
The price of Really Nice Pen is $150.00
看起来不错,所以你可能会认为这也适用于其他产品:
document.write("The price of " + products[1].title + " is $" + products[2].price.toPrecision(5));
document.write("The price of " + products[2].title + " is $" + products[2].price.toPrecision(5));
The price of Golf Shirt is $49.990
The price of My Car is $1234.6
document.write("The price of " + products[0].title + " is $" + products[0].price.toFixed(2));
document.write("The price of " + products[1].title + " is $" + products[2].price.toFixed(2));
document.write("The price of " + products[2].title + " is $" + products[2].price.toFixed(2));
The price of Really Nice Pen is $150.00
The price of Golf Shirt is $49.99
The price of My Car is $1234.56
const num1 = 123.4567;
// if no arguments are passed, it is similar to converting the Number to String
num1.toPrecision(); // returns "123.4567
// scientific notation is used when you pass precision count less than total
// number of digits left of the period
num1.toPrecision(2); // returns "1.2e+2"
// last digit is rounded if precision is less than total significant digits
num1.toPrecision(4); // returns "123.5"
num1.toPrecision(5); // returns "123.46"
const largeNum = 456.789;
largeNum.toPrecision(2); // returns "4.6e+2"
// trailing zeroes are added if precision is > total digits of the number or float
num1.toPrecision(9); // returns "123.456700"
const num2 = 123;
num2.toPrecision(4); // returns "123.0"
const num3 = 0.00123;
num3.toPrecision(4); // returns "0.001230"
num3.toPrecision(5); // returns "0.0012300"
// if the number is < 1, precision is by the significant digits
num3.toPrecision(1); // returns "0.001"
toFixed()以四舍五入的定点表示法返回一个表示 Number 对象的 String。这个函数只关心小数点数
const num1 = 123.4567;
// if no argument is passed, the fractions are removed
num1.toFixed(); // returns "123"
// specifying an argument means you the amount of numbers after the decimal point
num1.toFixed(1); // returns "123.5"
num1.toFixed(3); // returns "123.457"
num1.toFixed(5); // returns "123.45670"
num1.toFixed(7); // returns "123.4567000"
// trying to operator on number literals
2.34.toFixed(1); // returns "2.3"
2.toFixed(1); // returns SyntaxError
(2).toFixed(1); // returns "2.0"
(2.34e+5).toFixed(1); // returns "234000.0"