召冠的博客

做对的事,脚踏实地,保持正直。
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

大数值的精度与格式化显示问题

Posted on 2025-10-28 14:37  江城2211  阅读(4)  评论(0)    收藏  举报

问题描述:

Java后端的默认序列化方法:

  • 当数值过大(如 1000000000000000000.00)或过小(如 0.0000000001)时,会默认使用科学计数法序列化(如 1E+181E-10

JavaScript 原生 Number 类型有安全范围(±9007199254740991),当数值超出这个范围时:

  • 原生 JSON.parse() 会自动截断末尾数字(精度丢失);
  • 原生 JSON.stringify() 会将大整数转为科学计数法(如 1234567890123456789 变为 1.2345678901234568e+18

 

解决方法:

1、Java后端序列化时,可通过指定序列化格式的配置,避免BigDecimal被序列化为科学计数法,确保以 “普通数字字符串” 形式输出(即 plain format)

  • SerializerFeature.WriteBigDecimalAsPlain 是Fastjson用于控制BigDecimal类型序列化格式的核心配置项
  • SerializationFeature.WRITE_BIGDECIMAL_AS_PLAIN 是Jackson用于控制BigDecimal类型序列化格式的核心配置项

 

public static void main(String[] args) throws Exception {

    // Jackson序列化处理的关键配置

    ObjectMapper om = new ObjectMapper();

    om.configure(JsonGenerator.Feature.WRITE_BIGDECIMAL_AS_PLAIN,true);

    // om.enable(JsonGenerator.Feature.WRITE_BIGDECIMAL_AS_PLAIN);

    BigDecimal b = new BigDecimal("0.0000000000123");

    String str1 = om.writeValueAsString(b);

 

     // Fastjson序列化处理decimal的关键配置

    String str2= JSON.toJSONString(b, SerializerFeature.WriteBigDecimalAsPlain);

     System.out.println();

}

 

2、WEB前端可引入json-bigint

JSONbig 是一个专门用于处理大整数 / 大数值的 JSON 解析器和序列化工具,核心解决 JavaScript 原生 JSON 处理超大数值时的精度丢失问题。

 

  • JSONbig.parse(jsonStr, [options]):解析 JSON 字符串,超大数值会被转为 BigInt 类型;
  • JSONbig.stringify(value, [replacer], [space]):序列化值,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))

// 对于JSONbig 它在处理数据时,会自动识别其中的 大数, 并以数组的格式保存起来

console.log(JSONbig.parse(str).id.toString()) // 1253585734669959168