jhr924 2024-03-05 16:33 采纳率: 0%
浏览 17
已结题

求js 四舍五入保留两位小数的方法。

例如数字 32.925 四舍五入后是32.93, 129.075四舍五入后是129.08。下面两个方法都不行

function myFixed2(num, digit) {
  num = parseFloat(num);
  return (Math.round((num + Number.EPSILON) * Math.pow(10, digit)) / Math.pow(10, digit)).toFixed(digit);
}
//
function myFixed(num, fixed) {//修改js四舍五入
     var pos = num.toString().indexOf('.'),
     decimal_places = num.toString().length - pos - 1,
     _int = num * Math.pow(10, decimal_places),
     divisor_1 = Math.pow(10, decimal_places - fixed),
     divisor_2 = Math.pow(10, fixed);
     return Math.round(_int / divisor_1) / divisor_2;
 }

  • 写回答

26条回答 默认 最新

  • 专家-百锦再 全栈领域优质创作者 2024-03-05 16:34
    关注
    获得0.30元问题酬金

    function roundToFixed(num, fixed) {return (Math.round((num + Number.EPSILON) * Math.pow(10, fixed)) / Math.pow(10, fixed));
    }
    function roundToFixed(num, fixed) {var pos = num.toString().indexOf('.'),decimal_places = num.toString().length - pos - 1,_int = num * Math.pow(10, decimal_places),divisor_1 = Math.pow(10, decimal_places - fixed),divisor_2 = Math.pow(10, fixed);
    return Math.round(_int / divisor_1) / divisor_2;
    }

    使用示例:

    console.log(roundToFixed(32.925, 2));
    // 输出 32.93console.log(roundToFixed(129.075, 2));
    // 输出 129.08

    有问题你别着急,评论留言都可以,看到马上就回复,尽量及时补充齐
    评论

报告相同问题?

问题事件

  • 系统已结题 3月13日
  • 创建了问题 3月5日

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题