最近项目需要对超大数(20几位数)进行基本运算,感觉天空飘来一片乌云~~
如果后台返回的大数不是字符串的话,返回的数值就会变成科学计数法的值,将科学计数法转成字符串也麻烦。
推荐大数计算插件:
big-integer
看描述说可以计算var largeNumber = bigInt("75643564363473453456342378564387956906736546456235345");
这么大的数,于是尝试了一下。
说明中有一段:Note that Javascript numbers larger than 9007199254740992 and smaller than -9007199254740992 are not precisely represented numbers and will not produce exact results. If you are dealing with numbers outside that range, it is better to pass in strings.
说明文档写明了所带方法,其中除法方法有两个(divide,divmod)一个不带余数,一个带余数。
divmod方法返回两个属性,quotient(整数部分),remainder(小数部分)。
将整数部分和小数部分拼接:
bigInt('75643564363473453456342378564387').divmod(10000000000000).quotient.toString()+'.'+ bigInt('75643564363473453456342378564387').divmod(10000000000000).remainder.toString()
不过发现有一个范围的大数除以10的N次方后的结果不准确。
所以放弃。
bignumber
bignumber的使用方法和其他计算插件差不多。
科学计数法转换:
console.log(BigNumber(1.2000000001e+43).toString(10)) //12000000001000000000000000000000000000000000
除法:
BigNumber(1.2000000001e+43).div(1000000000000)
===============================此处分割线
对于大数计算,ES新推出了数据类型BigInt,只需要在数字末尾加n字母,就表示BigInt类型。
相关文档可转至:https://segmentfault.com/a/1190000019912017?utm_source=tag-newest