当前位置: 首页 > Web前端 > JavaScript

精度损失问题

时间:2023-03-26 23:03:29 JavaScript

背景BFFClient使用的npm包request-promise-native请求微服务接口返回ID精度丢失1713166949059674112=>1713166949059674000为什么会丢失?存储二进制时,小数点最大偏移量为52位。计算机存储的是二进制,能存储的二进制是62位的。如果超过,则会进行舍入操作。所以JS中能精确表示的最大整数是Math.pow(2,53),十进制为9007199254740992大于9007199254740992可能会丢精度参考:https://zhuanlan.zhihu.com/p/...request-promise-native请求时,当options.json不为false时,会使用JSON.parse解析bodyif(self._json){try{response.body=JSON.parse(response.body,self._jsonReviver)}catch(e){debug('invalidJSONreceived',self.uri.href)}}MinimumdemoBuildserviceAPI1.BuildJavaWebApi:Reference:BuildingaRESTfulWebService修改服务层使得id最小值大于js精度限制publiclonggetId(){returnid+1713166949059674112L;}*修改controller层添加post请求@PostMapping("/greeting_create")publicGreetingcreateGreeting(@RequestParam(value="name",defaultValue="World")Stringname){returnnewGreeting(counter.incrementAndGet(),String.format(模板,名称));二、请求GET请求:curlhttp://localhost:8080/greetingPOST请求:curl-XPOSThttp://localhost:8080/greeting_create{"id":1713166949059674120,"content":"Hello,World!"}解决方法一、获取响应体String,使用JSONbig将id转换为字符串。优点:只影响当前请求。缺点:不支持POST请求方式,不支持通过json传递参数。通过form+json传递参数:false需要后端接口支持GET请求constrp=require('request-promise-native');constjsonBigInt=require('json-bigint');constgetOptions={'method':'GET',json:false,'url':'http://localhost:8080/greeting',};constgetRes=awaitrp(getOptions);console.log('获取结果:',jsonBigInt.parse(getRes));POST请求:不支持,json被占用,会执行JSON.parseconstrp=require('request-promise-native');constjsonBigInt=require('json-bigint');constpostOptions={'method':'POST','url':'http://localhost:8080/greeting_create',json:{name:'test'},};constpostRes=awaitrp(postOptions);console.log('发布结果:',jsonBigInt.parse(postRes));2、使用JSONbig.parse()代替JSON.parse()优点:实现简单,支持POST缺点:影响所有JSON.parse()parseconstrp=require('request-promise-native');constjsonBigInt=require('json-bigint');异步函数jsonBigReplaceParse(){constoldParse=JSON.parse;JSON.parse=jsonBigInt.parse;constpostOptions={'method':'POST','url':'http://localhost:8080/greeting_create',json:{name:'test'},};constpostRes=awaitrp(postOptions);console.log('发布结果:',postRes);JSON.parse=oldParse;}~~本文到此结束,感谢阅读!~学习有趣的知识,认识有趣的朋友,塑造有趣的灵魂!大家好,我是〖编程三昧〗的作者王隐,我的公众号是《编程三昧》,欢迎关注,希望大家多多指教!