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

时间:2022-04-25
本文章向大家介绍一个数字截取引发的精度问题(三),主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

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

let numObj = 12345.6numObj.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+1console.log(numObj.toExponential(4)); // logs 7.7123e+1console.log(numObj.toExponential(2)); // logs 7.71e+1console.log(77.1234.toExponential()); // logs 7.71234e+1console.log(77 .toExponential());     // logs 7.7e+1

注意:

  1. fractionDigits 取 0~20之间,其实就是小数点后有几个数字。
  2. 若numObj是一个没有小数点或者非指数形式的数字字面量,在调用时需要加一个空格,以防止解释器将"点"解释为小数点。

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