js四舍五入函数

不念不忘少年蓝@ 2022-05-08 00:14 291阅读 0赞

方法一:写一个简单的了函数

  1. //四舍五入函数
  2. var round = function (num, digits) {
  3. return Math.round(num * Math.pow(10, digits)) / Math.pow(10, digits);
  4. };
  5. round(0.455, 2); // 结果:0.46

方法二:为Number增加一个round方法

  1. //为Number类型增加round方法
  2. delete Number.prototype.round;
  3. Number.prototype.round=function (digits) {
  4. var num = this;
  5. return Math.round(num * Math.pow(10, digits)) / Math.pow(10, digits);
  6. };
  7. 0.455.round(2); //结果:0.46

发表评论

表情:
评论列表 (有 0 条评论,291人围观)

还没有评论,来说两句吧...

相关阅读