超大数字四舍五入保留N位小数【没bug】

大部分npm常用的插件四舍五入都是用数值直接去计算四舍五入的存在精度问题,本方法是用用字符串拆分比较整数大小,这样就避开了精度的问题;

该方法可以传入:1.134、99.99、9999999999999999999.99999、.001、12.、0.、00.、类似的奇葩字符都会自动处理补全

代码如下:

javascript 复制代码
function setRound(v, n) {
  if(isNaN(v)) return 'NaN';
  const values = v.split(".");
  function get0(lastV){
    // 补0函数
    var s0 = lastV + '0000000000000000000000'
    return s0.substring(0, n)
  }
  let integerStr = values[0];
  let decimalStr2 = values[1].substring(0, n)
  let decimalStr = values[1].substring(0, n+1);
  const lastN = Number(decimalStr.slice(-1));
  if(!values[1]) return integerStr + "." + get0(decimalStr2);
  if(decimalStr && decimalStr.length > n){ // 小数位超过n位数
    if(lastN >= 5){
      decimalStr2 = decimalStr2 - 0 + 1 // 五入
      if(decimalStr2.toString().length > n){ // 如果小数位超过n+1位数
        decimalStr2 = get0('0')
        integerStr = Number(integerStr) + 1
      }
    }
  }
  integerStr = Number(integerStr) // 规范00.134、.134这种整数位
  return integerStr + "." + get0(decimalStr2)
}
相关推荐
_柳青杨14 小时前
深入理解 JavaScript 事件循环
前端·javascript
大家的林语冰19 小时前
ES5 凉凉,Babel 8 正式发布,默认不再编译为 ES5 和 CJS......
前端·javascript·前端工程化
weedsfly1 天前
异步编程全景与事件循环——彻底搞懂 JS 执行机制
前端·javascript
用户1733598075371 天前
纯前端 PDF 数字签名实战:Vue 3 + pdf-lib 在浏览器里完成签名嵌入
前端·javascript
JieE2121 天前
LeetCode 226. 翻转二叉树|JS 递归超详细拆解,二叉树入门经典题
javascript·算法
JieE2121 天前
LeetCode 104. 二叉树的最大深度|递归思路超详细拆解
javascript·算法
kyriewen2 天前
我用 AI 一周写完了整个项目,上线第一天就崩了——这是我踩过最贵的 5 个坑
前端·javascript·ai编程
Larcher2 天前
AI Loop:让AI像人一样自主完成任务的核心机制
javascript·人工智能·设计模式
默_笙2 天前
🃏 JS 只有 8 种数据类型,但我花了 2 天才搞懂 null 和 undefined 的区别
javascript
jump_jump2 天前
流式 HTML:从 htmx 片段装配到浏览器原生增量渲染
javascript·性能优化·前端工程化