精度丢失问题

2022-02-03  本文已影响0人  隐逸王
精度丢失问题.001

背景

1713166949059674112 => 1713166949059674000

为什么会丢失?

if (self._json) {
  try {
    response.body = JSON.parse(response.body, self._jsonReviver)
  } catch (e) {
    debug('invalid JSON received', self.uri.href)
  }
}

最小 demo

搭建服务 API

一、搭建 Java Web Api:

    public long getId() {
        return id + 1713166949059674112L;
    }
* 修改 controller 层添加 post 请求
    @PostMapping("/greeting_create")
    public Greeting createGreeting(@RequestParam(value = "name", defaultValue = "World") String name) {
        return new Greeting(counter.incrementAndGet(), String.format(template, name));
    }

二、请求

{"id":1713166949059674120,"content":"Hello, World!"}

解决方案

1. 获取响应体的字符串,使用 JSONbigid 转化成字符串

const rp = require('request-promise-native');
const jsonBigInt = require('json-bigint');

  const getOptions = {
    'method': 'GET',
    json: false,
    'url': 'http://localhost:8080/greeting',
  };

  const getRes = await rp(getOptions);
  console.log('get result: ', jsonBigInt.parse(getRes));
const rp = require('request-promise-native');
const jsonBigInt = require('json-bigint');

  const postOptions = {
    'method': 'POST',
    'url': 'http://localhost:8080/greeting_create',
    json: { name: 'test' },
  };
  const postRes = await rp(postOptions);
  console.log('post result: ', jsonBigInt.parse(postRes));

2. 使用 JSONbig.parse() 替换 JSON.parse()

const rp = require('request-promise-native');
const jsonBigInt = require('json-bigint');

async function jsonBigReplaceParse() {
  const oldParse = JSON.parse;
  JSON.parse = jsonBigInt.parse;
  const postOptions = {
    'method': 'POST',
    'url': 'http://localhost:8080/greeting_create',
    json: { name: 'test' },
  };
  const postRes = await rp(postOptions);
  console.log('post result: ', postRes);
  JSON.parse = oldParse;
}

~

~ 本文完,感谢阅读!

~

学习有趣的知识,结识有趣的朋友,塑造有趣的灵魂!

大家好,我是〖编程三昧〗的作者 隐逸王,我的公众号是『编程三昧』,欢迎关注,希望大家多多指教!

上一篇 下一篇

猜你喜欢

热点阅读