一个数字截取引发的精度问题(三)

上次总结的第四条: 当传入的参数小于数字的整数位时,返回指数形式表示的字符串。

let numObj = 12345.6
numObj.toPrecision(2) // '1.2e+4'

在JavaScript中有一个专门返回数字的指数形式的方法:toExponential()

numObj.toExponential([fractionDigits])

解释:

A string representing the given Number object in exponential notation with one digit before the decimal point, rounded to fractionDigits digits after the decimal point.

大意:

返回一个小数点前有一位数字且已按照小数点后指定的位数(fractionDigits)四舍五入后的指数形式的字符串。

let numObj = 77.1234;

console.log(numObj.toExponential());  // logs 7.71234e+1
console.log(numObj.toExponential(4)); // logs 7.7123e+1
console.log(numObj.toExponential(2)); // logs 7.71e+1
console.log(77.1234.toExponential()); // logs 7.71234e+1
console.log(77 .toExponential());     // logs 7.7e+1

注意:

  1. fractionDigits 取 0~20之间,其实就是小数点后有几个数字。
  2. 若numObj是一个没有小数点或者非指数形式的数字字面量,在调用时需要加一个空格,以防止解释器将"点"解释为小数点。
  3. 此方法也会进行四舍五入,作为金额计算时,要多加注意。

下篇将探究一下,经典问题:0.1 + 0.2 != 0.3。

获得最新文章,请关注:

一个数字截取引发的精度问题(三)_第1张图片
Paste_Image.png

你可能感兴趣的:(一个数字截取引发的精度问题(三))