• 技术文章 >Web开发 >JavaScript

    js四舍五入保留2位小数

    宋雪维宋雪维2021-01-28 16:43:11原创26693

    在之前python的学习中,我们知道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:把一个数字舍入为它最接近的整数,>=0.5入,<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位小数的两种方法,大家可以直接套用代码使用哟~

    专题推荐:javascript
    品易云
    上一篇:js四舍五入保留小数点后两位 下一篇:js四舍五入的函数

    相关文章推荐

    • python中pivot()函数是什么?• python中uuid模块是什么?• 如何使用python中threadpool模块?• python中pickle模块是什么?

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网