js中的数字精度

67 阅读1分钟

Math.round()

Math.round() 函数返回一个数字四舍五入后最接近的整数。

Math.round(Math.PI) // output 3
Math.round(Math.E) // output 3
Math.round(-3.845) // output -4

Math.ceil()

Math.ceil() 函数返回大于或等于一个给定数字的最小整数。

Math.ceil(Math.PI) // output 4
Math.ceil(Math.E) // output 3
Math.ceil(-3.845) // output -3

Math.trunc

Math.trunc() 方法会将数字的小数部分去掉,只保留整数部分。

Math.trunc(Math.PI) // output 3
Math.trunc(Math.E) // output 2
Math.trunc(-3.845) // output -3

toFixed

toFixed() 方法使用定点表示法来格式化一个数值,不指定小数位时也可以用来取整,返回的是字符串格式。

Math.PI.toFixed() // output '3'
Math.E.toFixed() // output '3'
(-3.845).toFixed() // output '-4'

toPrecision

toPrecision() 方法以指定的精度返回该数值对象的字符串表示,以定点表示法或指数表示法表示的一个数值对象的字符串表示,四舍五入到 precision 参数指定的显示数字位数。(多个0时,会返回科学计数法字符串,需要转化为数字表示时,加上Number即可。)

Math.PI.toPrecision(1) // output '3'
Math.E.toPrecision(1) // output '3'
(-3.845).toPrecision(1) // output '-4'
(.01465463).toPrecision(2) // output 0.015
(146546.3).toPrecision(2) // output 1.5e+5
Number(1.5e+5) // output 150000

Math.fround()

Math.fround() 可以将任意的数字转换为离它最近的单精度浮点数形式的数字。在js中0.1 + 0.2不等于0.3,这个时候可以用Math.fround来解决这个问题。

0.1 + 0.2 === 0.3 // false
Math.fround(0.1 + 0.2) == Math.fround(0.3) // true