You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular项目读取JSON时如何保留精确十进制值?

解决Angular中加载JSON时数值精度丢失问题

问题根源

JavaScript的Number类型是双精度浮点数,仅能精确表示2^53以内的整数。你JSON中的这类带多位小数的数值,超出精度范围后会被自动四舍五入——不管是直接import JSON还是用HttpClient请求,底层都是调用JSON.parse,因此都会出现这个问题。

解决方案:读取原始文本并自定义解析

要保留原始数字格式,需要先把JSON文件当作纯文本读取,再手动处理数值为字符串(或用第三方库保留精度),避免默认解析转成Number类型。

方法1:HttpClient读取纯文本+自定义正则替换

通过HttpClient获取JSON原始文本,再用正则将指定数值字段转为字符串后解析:

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';

@Injectable({ providedIn: 'root' })
export class MyService {
  private myJson: any;

  constructor(private http: HttpClient) {
    this.loadJson();
  }

  private async loadJson() {
    // 以纯文本形式获取JSON文件
    const rawText = await this.http.get('assets/MyJson.json', { responseType: 'text' }).toPromise();
    // 将目标数值字段转为字符串
    const processedText = rawText
      .replace(/"valueA":\s*(-?\d+\.?\d*)/g, '"valueA": "$1"')
      .replace(/"valueB":\s*(-?\d+\.?\d*)/g, '"valueB": "$1"');
    // 解析为对象
    this.myJson = JSON.parse(processedText);
  }

  public getFieldsIWant() {
    return this.myJson.theFields?.iWant;
  }
}

这种方式精准控制需要处理的字段,避免误改其他内容。

方法2:使用第三方库处理精度

如果JSON中有大量高精度数值,推荐使用json-bigint库自动处理超出精度的数值为字符串:

  1. 安装依赖:
npm install json-bigint
  1. 在服务中使用:
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import JSONbig from 'json-bigint';

@Injectable({ providedIn: 'root' })
export class MyService {
  private myJson: any;
  // 配置库将超出精度的数值存为字符串
  private jsonParser = JSONbig({ storeAsString: true });

  constructor(private http: HttpClient) {
    this.loadJson();
  }

  private async loadJson() {
    const rawText = await this.http.get('assets/MyJson.json', { responseType: 'text' }).toPromise();
    // 用自定义解析器处理
    this.myJson = this.jsonParser.parse(rawText);
  }

  public getFieldsIWant() {
    return this.myJson.theFields?.iWant;
  }
}

这个库会自动识别所有超出JS Number精度的数值,转为字符串保留原始内容,比手动写正则更可靠。


内容的提问来源于stack exchange,提问作者KastenBrot

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 05:18:19