在之前python的学习中js 四舍五入 两位小数,我们知道python是可以进行四舍五入计算的,而JavaScript也是可以的。本文主要介绍JavaScript中四舍五入保留2位小数的两种方法,即toFixed()方法和Math.round方法。
方法一:使用toFixed()方法,
toFixed(n):把一个数按照银行家舍入规则进行舍入,也就是四舍五入保留n位小数。
实例:四舍五入保留2位小数
var a = 22.3344
//undefined
a.toFixed(2)
//"22.33"
a = 22.3355
//22.3355
a.toFixed(2)
//"22.34"
方法二:使用Math.round方法
Math.round:把一个数字舍入为它最接近的整数js 四舍五入 两位小数,>=0.5入,
实例:把不同的数舍入为最接近的整数
Math.round(0.60)
Math.round(0.50)
Math.round(0.49)
Math.round(-4.40)
Math.round(-4.60)
输出
1
1
0
-4
-5
以上就是JavaScript中四舍五入保留2位小数的两种方法,大家可以直接套用代码使用哟~
!
发表评论