JS中大数字问题(在Vue项目中的解决办法)

923 阅读1分钟

问题描述

  当在js中表示一个超大数字时,对任何安全范围内的数字进行计算可能不能保持精度,即得到的结果有误。

解决方案

(1)使用js的最新基本数据类型:Bigint。
(2)在Vue项目中,使用第三方包npm i json-bigint,如:

import JSONbig from 'json-bigint'

const str = '{ "id": 1253585734669959168 }'

console.log(JSON.parse(str)) // 1253585734669959200

// 它会把超出 JS 安全整数范围的数字转为一种类型为 BigNumber 的对象
// 我们在使用的时候需要把这个 BigNumber.toString() 就能得到原来正确的数据了
console.log(JSONbig.parse(str))
console.log(JSONbig.parse(str).id.toString()) // 1253585734669959168

const data = JSONbig.parse(str)

console.log(JSON.stringify(data))
console.log(JSONbig.stringify(data))

Vue中使用axios发出请求,axios默认对返回的原始数据使用JSON.parse进行处理,而axios提供一个API用来自己定义对原始数据的处理:

const request = axios.create({
  baseURL: '', 
  // 定义后端返回的原始数据的处理
  // 参数 data 就是后端返回的原始数据(未经处理的 JSON 格式字符串)
  transformResponse: [function (data) {
    // 后端返回的数据可能不是 JSON 格式字符串,如果不是的话,那么 JSONbig.parse 调用就会报错所以我们使用 try-catch 来捕获异常,处理异常的发生
    try {
      return JSONbig.parse(data)
    } catch (err) {
      console.log('转换失败', err)
      // 如果转换失败,直接返回
      return data
    }
  }]
})