js 四舍五入简单实现,由于toFixed()是银行家舍入法

/**
 * 四舍五入("数字" 或 "数字字符串")
 * @param {number} precision 小数精度
 * @param {boolean} sup 自动补0,默认true
 */
function toRound(precision, sup = true) {
  // 四舍五入方法
  const round = (number, precision) => {
    precision = precision == null ? 0 : precision >= 0 ? Math.min(precision, 292) : Math.max(precision, -292)
    if (precision) {
      let pair = `${number}e`.split('e')
      const value = Math.round(`${pair[0]}e${+pair[1] + precision}`)
      pair = `${value}e`.split('e')
      return +`${pair[0]}e${+pair[1] - precision}`
    }
    return Math.round(number)
  }
  // 取出 "数字" 和 "."
  let val = this + ''
  // NaN抛出异常,并返回 val
  if (isNaN(val)) {
  	console.error('toRound can only be executed number or srting of number')
  	return val
  }
  // 正负数处理
  let value = val > 0 ? round(val, precision) : -round(-val, precision)
  // 是否补0
  return sup ? value.toFixed(precision) : value
}

// 挂载Number、String原型链中
Number.prototype.toRound = toRound
String.prototype.toRound = toRound

请测试以下用例 (当保留2位小数时)

toFixed的修约 (舍入) 规则并不是“四舍五入”,而是“四舍六入五成双”也即“4舍6入5凑偶”。
这里“四”是指4 时舍去,"六"是指26时进上,"五"指的是根据5后面的数字来定,当5后有有效数字(不为0) 时,舍5入1; 当5后无有效数字时,需要分两种情况来讲D5前为奇数,舍5入1;(5前为偶数,舍5不进。 (0是偶数)

const arr = [0.046, 0.044, 0.0451, 0.0450, 0.04503, 0.045, 0.035]
const arr2 = [], arr3 = []
arr.forEach(item => arr2.push(item.toFixed(2)))
arr.forEach(item => arr3.push(item.toRound(2)))
console.log(arr)  // [0.046,   0.044,  0.0451, 0.045,  0.04503,  0.045,  0.035]
console.log(arr2) // ['0.05', '0.04', '0.05', '0.04', '0.05',   '0.04', '0.04']
console.log(arr3) // ['0.05', '0.04', '0.05', '0.05', '0.05',   '0.05', '0.04']

请注意:第四、第六 的变化

其中 round 核心方法来自于 lodash 仓库地址: https://github.com/lodash/lodash

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值