toFixed 四舍五入问题

项目中使用了计算之后四舍五入

例子:数量 * 单价 = 总价
		5 *  2.093 = 10.465  使用toFixed四舍五入保留两位小数却是 10.46

1、使用 Math.toFixed() 函数

1)方法介绍

toFixed() 方法可以将数字转换为字符串,并指定小数点后保留几位。如果小数实际位数不够指定的位数,不足的部分会补 0。所有主要浏览器都支持 toFixed() 方法。

toFixed() 使用的是银行家舍入规则:四舍六入五取偶(又称四舍六入五留双)

2)银行家舍入法:
四舍六入五考虑,五后非零就进一,五后为零看奇偶,五前为偶应舍去,五前为奇要进一

使用toFixed()函数,有可能会出现精度问题,可以考虑到用Math.round()函数‘

自定义函数 customToFixed (解决小数点最后一位为5的情况)

export function customToFixed(x, n) {
  let f_x = parseFloat(x)
  if (isNaN(f_x)) {
    console.warn('传递参数不是数字!')
    return false
  }
  f_x = Math.round(x * Math.pow(10, n)) / Math.pow(10, n)
  let s_x = f_x.toString()
  let pos_decimal = s_x.indexOf('.')
  if (pos_decimal < 0) {
    pos_decimal = s_x.length
    s_x += '.'
  }
  while (s_x.length <= pos_decimal + n) {
    s_x += '0'
  }
  return s_x
}

相关推荐

  1. toFixed 四舍五入问题

    2024-07-11 00:34:05       24 阅读
  2. 解决toFixed精度问题

    2024-07-11 00:34:05       49 阅读
  3. 四舍五入专题

    2024-07-11 00:34:05       52 阅读
  4. Swift 中如何四舍五入

    2024-07-11 00:34:05       30 阅读
  5. js toPrecision() 和toFixed() 方法是什么和例子

    2024-07-11 00:34:05       53 阅读
  6. php小数四舍五入、向上取整、向下取整

    2024-07-11 00:34:05       53 阅读
  7. [office] excel中四舍五入的教程 #经验分享#媒体

    2024-07-11 00:34:05       48 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-11 00:34:05       100 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-11 00:34:05       107 阅读
  3. 在Django里面运行非项目文件

    2024-07-11 00:34:05       90 阅读
  4. Python语言-面向对象

    2024-07-11 00:34:05       98 阅读

热门阅读

  1. [C++][CMake][嵌套的CMake]详细讲解

    2024-07-11 00:34:05       22 阅读
  2. 65.指针函数和函数指针

    2024-07-11 00:34:05       26 阅读
  3. 网络安全测评技术与标准

    2024-07-11 00:34:05       28 阅读
  4. Qt之多线程编程(QThread)

    2024-07-11 00:34:05       27 阅读
  5. MySQL:left join 后用 on 还是 where?

    2024-07-11 00:34:05       24 阅读
  6. 最短路径算法(算法篇)

    2024-07-11 00:34:05       25 阅读
  7. 【数学建模】生产企业原材料的订购与运输

    2024-07-11 00:34:05       24 阅读
  8. Spring Boot与Traefik的集成

    2024-07-11 00:34:05       28 阅读
  9. vue详解

    vue详解

    2024-07-11 00:34:05      22 阅读