toPrecision、toFixed 和 Math.round 的区别

JavaScript 中三种数字格式化方法的使用场景和区别

问题

toPrecisiontoFixedMath.round 这三个方法有什么区别?

解答

toPrecision - 控制有效数字

toPrecision 用于格式化数字的有效数字位数,从左至右第一个不为 0 的数字开始计数。

const num = 123.456;

num.toPrecision(4);  // "123.5"
num.toPrecision(2);  // "1.2e+2"

const num2 = 0.00123;
num2.toPrecision(2); // "0.0012"

toFixed - 控制小数位数

toFixed 用于格式化小数点后的位数,从小数点开始计数,返回字符串。

const num = 123.456;

num.toFixed(2);  // "123.46"
num.toFixed(0);  // "123"
num.toFixed(4);  // "123.4560"

Math.round - 四舍五入取整

Math.round 将数字四舍五入到最接近的整数,返回数字类型。

Math.round(123.456);  // 123
Math.round(123.5);    // 124
Math.round(-123.5);   // -123
Math.round(-123.6);   // -124

关键点

  • toPrecision(n) 控制总有效数字位数,返回字符串
  • toFixed(n) 控制小数点后位数,返回字符串
  • Math.round() 四舍五入到整数,返回数字
  • toPrecisiontoFixed 都会进行四舍五入,但计数起点不同
  • 需要数字类型时记得用 Number()parseFloat() 转换