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

如何将JSON数据中的金额格式化为印度卢比(INR)数字格式

格式化JSON中的金额为印度卢比格式

可以利用JavaScript的Intl.NumberFormatAPI实现印度卢比的数字分组格式(如12,43,434),以下是具体实现步骤和代码:

步骤说明

  1. 将原始JSON字符串解析为JavaScript对象数组
  2. 使用Intl.NumberFormat('en-IN')创建符合印度数字分组规则的格式化器
  3. 遍历每个账户对象,将字符串类型的金额转为数字后格式化
  4. 将处理后的对象转回格式化后的JSON字符串

代码示例

原始JSON

[
    {
        "id": "1",
        "accountName": "Account 1",
        "debitAmount": "15453435",
        "creditAmount":"313244"
        
    },
    {
        "id": "2",
        "accountName": "Account 2",
        "debitAmount": "15453435",
        "currencyCode": "INR",
        "creditAmount":"313244"
        
    }
]

处理代码

// 原始JSON字符串
const rawJson = `[
    {
        "id": "1",
        "accountName": "Account 1",
        "debitAmount": "15453435",
        "creditAmount":"313244"
        
    },
    {
        "id": "2",
        "accountName": "Account 2",
        "debitAmount": "15453435",
        "currencyCode": "INR",
        "creditAmount":"313244"
        
    }
]`;

// 解析为对象数组
const accounts = JSON.parse(rawJson);

// 创建印度数字格式的格式化器
const inrNumberFormatter = new Intl.NumberFormat('en-IN');

// 遍历处理每个账户的金额字段
const formattedAccounts = accounts.map(account => ({
    ...account,
    debitAmount: inrNumberFormatter.format(Number(account.debitAmount)),
    creditAmount: inrNumberFormatter.format(Number(account.creditAmount))
}));

// 转换为格式化后的JSON
const formattedJson = JSON.stringify(formattedAccounts, null, 2);
console.log(formattedJson);

输出结果

[
  {
    "id": "1",
    "accountName": "Account 1",
    "debitAmount": "1,54,53,435",
    "creditAmount": "3,13,244"
  },
  {
    "id": "2",
    "accountName": "Account 2",
    "debitAmount": "1,54,53,435",
    "currencyCode": "INR",
    "creditAmount": "3,13,244"
  }
]

额外说明

  • 如果需要带印度卢比符号(₹),可以修改格式化器配置:
    const inrCurrencyFormatter = new Intl.NumberFormat('en-IN', {
        style: 'currency',
        currency: 'INR'
    });
    
    此时格式化后的金额会变成₹1,54,53,435这种形式。
  • 确保金额字段是有效的数字字符串,转换时可以根据需要添加错误处理逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 13:20:29