JavaScript中保留2位小数的四舍五入方法,你知道吗?

  在之前python的学习中js 四舍五入 两位小数,我们知道python是可以进行四舍五入计算的,而JavaScript也是可以的。本文主要介绍JavaScript中四舍五入保留2位小数的两种方法,即toFixed()方法和Math.round方法。

  方法一:使用toFixed()方法,

  toFixed(n):把一个数按照银行家舍入规则进行舍入,也就是四舍五入保留n位小数。

  实例:四舍五入保留2位小数

  <pre class="brush:php;toolbar:false">var a = 22.3344
//undefined
a.toFixed(2)
//"22.33"
a = 22.3355
//22.3355
a.toFixed(2)
//"22.34"</pre>

  方法二:使用Math.round方法

  Math.round:把一个数字舍入为它最接近的整数js 四舍五入 两位小数,>=0.5入,

  实例:把不同的数舍入为最接近的整数

  <pre class="brush:php;toolbar:false">Math.round(0.60)
Math.round(0.50)
Math.round(0.49)
Math.round(-4.40)
Math.round(-4.60)</pre>

  输出

  <pre class="brush:php;toolbar:false">1
1
0
-4
-5</pre>

  以上就是JavaScript中四舍五入保留2位小数的两种方法,大家可以直接套用代码使用哟~

文章由官网发布,如若转载,请注明出处:https://www.veimoz.com/1475
0 评论
531

发表评论

!