接口返回數據中攜帶有id字段,如果數值過大,在顯示的時候會發現精度丟失。
當然,前端解析響應數據後,也在所難免發生精度丟失問題。
代碼如下:
var text = '{"id":18014398509481985}';
var obj = JSON.parse(text);
console.log(obj);
//結果: {id: 18014398509481984}
解決辦法:
- 後端將ID處理成字符串的形式
- 前端通過正則,處理返回的響應數據,轉換成字符串
var text = '{"id":18014398509481985}';
const id= text.match(/\d{17,}/)[0]; // 正則獲取大於17位數字的值
text = text.replace(id,`"${id}"`); // 補上雙引號
const data = JSON.parse(text);
//結果: {id: "18014398509481985"}