toFixed()与银行家舍入

一直在用toFixed()方法做浮点数的舍入取值,如果只是客户端展示数据是没有多大问题的,但是如果涉及到和后端互交,数据的精度可能会导致接口对接失败,当然了,涉及安全性的数值,比如金额之类的不应该放在前端计算,应该以后端为准,少数情况下如果需要的时候,则需要修复其精度

1.出现问题的场景

  1. 首先,我们发现在ie浏览器与其他的主流浏览器中,由于二进制下浮点数的存储问题,toFixed()的行为是不一样的,也说明了各浏览器厂家的做法不一致。

在ie11中:

10.015.toFixed(2)
2// 打印结果:"0.02"

在chrome中:

10.015.toFixed(2)
2// 打印结果:"0.01"

对于此类问题,部分场景是不可接受的,测试可能会打出一个兼容性的bug

  1. 其次,我们虽然知道,toFixed()是一种银行家舍入,但是他确是入五取单,而不是银行家舍入所说的入五取双,同样是银行家舍入,此函数计算精度与后台java等语言的银行家舍入精度不同,可能照成接口验证失败。

在前端浏览器中:

10.025.toFixed(2)
2// 打印结果:"0.03"
30.035.toFixed(2)
4// 打印结果:"0.03"

在后端服务器中:

10.025.setScale(2,RoundingMode.HALF_EVEN)
2// 打印结果:"0.02"
30.035.setScale(2,RoundingMode.HALF_EVEN)
4// 打印结果:"0.04"

事实上,正确的做法应该是:有关金额的运算应该完全交由后端计算,然后交给前端展示

2.修复方案

方案很简单,我们只要重写Number.prototype.toFixed方法就可以了。

  1. 如果我们需要普通的四舍五入:

1/* eslint-disable no-extend-native */ // 规避eslint不可修改原型报错
2Number.prototype.originalToFixed = Number.prototype.toFixed // 保留原方法
3Number.prototype.toFixed = function(length = 0) { // 默认保留0位小数
4  let result
5  // 处理负数
6  let that = this
7  let isNegative = false
8  if (this < 0) {
9    isNegative = true
10    that = -this
11  }
12  let thisNum = that.toString()
13  if (thisNum.indexOf('.') === -1) thisNum = thisNum + '.0'
14  for (let i = 0; i < length; i++) {
15    thisNum = thisNum + '0'
16  }
17  const dotIndex = thisNum.indexOf('.')
18  thisNum = thisNum.slice(0, dotIndex) + thisNum.slice((dotIndex + 1), (dotIndex + 1 + length)) + '.' + thisNum.slice(dotIndex + 1 + length)
19  thisNum = Number(thisNum).toString()
20  const thisNumList = thisNum.split('.') // 分离整数与小数
21  if (thisNumList.length === 1) result = thisNum.toString() // 如果只有整数,则不需要处理
22  else {
23    if (Number(thisNumList[1][0]) >= 5) result = (Number(thisNumList[0]) + 1).toString() // 五入
24    else result = thisNumList[0] // 四舍
25  }
26  if (length === 0) return `${isNegative ? '-' : ''}${result}`
27  else {
28    while (result.length < length + 1) { // 如果位数不够,则用0补齐
29      result = '0' + result
30    }
31    return result.slice(0, (result.length - length)) + '.' + result.slice(result.length - length)
32  }
33}

  1. 如果我们需要使用正常的银行家舍入:

1/* eslint-disable no-extend-native */ // 规避eslint不可修改原型报错
2Number.prototype.originalToFixed = Number.prototype.toFixed // 保留原方法
3Number.prototype.toFixed = function(length = 0) { // 默认保留0位小数
4  let result
5  // 处理负数
6  let that = this
7  let isNegative = false
8  if (this < 0) {
9    isNegative = true
10    that = -this
11  }
12  let thisNum = that.toString()
13  if (thisNum.indexOf('.') === -1) thisNum = thisNum + '.0'
14  for (let i = 0; i < length; i++) {
15    thisNum = thisNum + '0'
16  }
17  const dotIndex = thisNum.indexOf('.')
18  thisNum = thisNum.slice(0, dotIndex) + thisNum.slice((dotIndex + 1), (dotIndex + 1 + length)) + '.' + thisNum.slice(dotIndex + 1 + length)
19  thisNum = Number(thisNum).toString()
20  const thisNumList = thisNum.split('.') // 分离整数与小数
21  if (thisNumList.length === 1) result = thisNum.toString() // 如果只有整数,则不需要处理
22  else {
23    if (Number(thisNumList[1][0]) > 5) result = (Number(thisNumList[0]) + 1).toString() // 六入
24    else if (Number(thisNumList[1][0]) < 5) result = thisNumList[0] // 四舍
25    else { // 判断5的情况
26      if (thisNumList[1].length > 1) result = (Number(thisNumList[0]) + 1).toString() // 如果5后还有位数则入
27      else {
28        if (Number(thisNumList[0][thisNumList[0].length - 1]) % 2 === 0) result = thisNumList[0] // 五前为偶应舍去
29        else result = (Number(thisNumList[0]) + 1).toString() // 五前为奇要进一
30      }
31    }
32  }
33  if (length === 0) return `${isNegative ? '-' : ''}${result}`
34  else {
35    while (result.length < length + 1) { // 如果位数不够,则用0补齐
36      result = '0' + result
37    }
38    return `${isNegative ? '-' : ''}${result.slice(0, (result.length - length)) + '.' + result.slice(result.length - length)}`
39  }
40}

这样就统一了舍入的精度,可以根据后台需要选择。



toFixed()与银行家舍入的更多相关文章

  1. JS013. 重写toFixed( )方法,toFixed()原理 - 四舍五入?银行家舍入法?No!六舍七允许四舍五入√!

    以下为场景实测与原理分析,需要重写函数请直接滚动至页尾!!! 语法 - Number.prototype.toFixed( ) // toFixed()方法 使用定点表示法来格式化一个数值. numO ...

  2. 关于BigDecimal 和 double 类型保存金钱,以及精度问题,银行家舍入法

    1. BigDecimal 类型数据 的创建,构造函数 有 public BigDecimal(BigInteger intVal, long val, int scale, int prec); p ...

  3. 四舍五入VS银行家舍入法

    在学习python的时候,遇见了一个颠覆了我传统观念的四舍五入. 看下面,round()的结果和我们以前根深蒂固的四舍五入是不同的. >>> round(0.5) 0 >> ...

  4. round函数——银行家舍入算法

    在处理四舍五入时,相信大部分人会使用math.round函数(不同的语言应该都有).有没有考虑过,这个函数是不是自己所需要的? po主碰到的问题是用来计算平均分.有个顶真的学生反映,明明是86.5,怎 ...

  5. 关于 JavaScript 的 精度丢失 与 近似舍入

    一.背景 最近做 dashborad 图表时,涉及计算小数且四舍五入精确到 N 位.后发现 js 算出来的结果跟我预想的不一样,看来这里面并不简单-- 二.JS 与 精度 1.精度处理 首先明确两点: ...

  6. tofixed方法 四舍五入

    tofixed方法 四舍五入 toFixed() 方法可把 Number 四舍五入为指定小数位数的数字.例如将数据Num保留2位小数,则表示为:toFixed(Num):但是其四舍五入的规则与数学中的 ...

  7. Javascript中 toFixed

    javascript中toFixed使用的是银行家舍入规则. 银行家舍入:所谓银行家舍入法,其实质是一种四舍六入五取偶(又称四舍六入五留双)法. 简单来说就是:四舍六入五考虑,五后非零就进一,五后为零 ...

  8. .NET压缩图片保存 .NET CORE WebApi Post跨域提交 C# Debug和release判断用法 tofixed方法 四舍五入 (function($){})(jQuery); 使用VUE+iView+.Net Core上传图片

    .NET压缩图片保存   需求: 需要将用户后买的图片批量下载打包压缩,并且分不同的文件夹(因:购买了多个用户的图片情况) 文章中用到了一个第三方的类库,Nuget下载 SharpZipLib 目前用 ...

  9. js toFixed()方法的坑

    javascript中toFixed使用的是银行家舍入规则. 银行家舍入:所谓银行家舍入法,其实质是一种四舍六入五取偶(又称四舍六入五留双)法. 简单来说就是:四舍六入五考虑,五后非零就进一,五后为零 ...

随机推荐

  1. Spring和MyBatis框架整合

    Spring集成MyBatis 使用MyBatis,需要创建MyBatis框架中的某些对象,使用这些对象,就能使用mybatis提供的功能了. 需要有Dao接口的代理对象,例如StudentDao接口 ...

  2. Docker——容器数据卷

    为什么需要容器数据卷 角度:遇到问题,尝试以朴素的道理解决问题.问题复杂化,解决的方式也变得复杂 问题的提出:docker将应用和环境打包成一个镜像,但是对于容器内的数据,如果不进行外部的保存,那么当 ...

  3. wifi钓鱼

    无线网络的加密方式和破解方式 1.WEP加密及破解 1).WEP加密方式 有线等效保密(wired euivalent pricacy,WEP)协议的使用RC4(rivest cipher4)串流加密 ...

  4. STM32芯片去除读写保护 | 使用ST-Link Utility去除STM32芯片读写保护

    1.使用ST-LINK V2下载器连接到STM32芯片, 点击Connect: 2.存在读保护: 3.修改选项字节(Option Bytes... ): 4.将读保护修改为Disabled. 5.打钩 ...

  5. STM32注意事项

    1. STM32 USB可配置在全速模式,时钟频率需为48MHz,且精度较高,无法使用芯片内部高速时钟实现(内部时钟精度一般为1%,但USB时钟需要0.1%) 2. 使用重映射功能时,需注意开启AFI ...

  6. 论文解读(MVGRL)Contrastive Multi-View Representation Learning on Graphs

    Paper Information 论文标题:Contrastive Multi-View Representation Learning on Graphs论文作者:Kaveh Hassani .A ...

  7. java == 和 equals

  8. 如何进行Hibernate的性能优化?

    大体上,对于HIBERNATE性能调优的主要考虑点如下: l 数据库设计调整 l HQL优化 l API的正确使用(如根据不同的业务类型选用不同的集合及查询API) l 主配置参数(日志,查询缓存,f ...

  9. 什么是 MyBatis 的接口绑定?有哪些实现方式?

    接口绑定,就是在 MyBatis 中任意定义接口,然后把接口里面的方法和 SQL 语句绑 定, 我们直接调用接口方法就可以,这样比起原来了 SqlSession 提供的方法我们可 以有更加灵活的选择和 ...

  10. Java 中,Comparator 与 Comparable 有什么不同?

    Comparable 接口用于定义对象的自然顺序,而 comparator 通常用于定义用户 定制的顺序.Comparable 总是只有一个,但是可以有多个 comparator 来定义 对象的顺序.