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

Intl.NumberFormat格式化数值过度舍入,需输出₹89.73L的问题

问题:调整Intl.NumberFormat紧凑格式化的小数位数

原代码使用Intl.NumberFormat对数值进行紧凑货币格式化时,结果被过度舍入:

let just_the_number = '8973565';

const just_the_number_formatted = Intl.NumberFormat("en-IN", { minimumFractionDigits: 0 }).format(parseFloat(just_the_number));
console.log(just_the_number_formatted)

let formatted_amount = new Intl.NumberFormat("en-IN", {
      style: "currency",
      currency: "INR",
      notation: "compact",
      compactDisplay: "long",
    }).format(just_the_number);

console.log(formatted_amount) // 输出 ₹90L

期望输出为₹89.73L,需要调整代码实现该需求。


解决方案

要保留两位小数的紧凑显示,只需在Intl.NumberFormat的配置中添加minimumFractionDigits和maximumFractionDigits参数并指定为2,强制格式化结果保留两位小数,覆盖默认的舍入规则。

修改后的代码如下:

let just_the_number = '8973565';

const just_the_number_formatted = Intl.NumberFormat("en-IN", { minimumFractionDigits: 0 }).format(parseFloat(just_the_number));
console.log(just_the_number_formatted)

let formatted_amount = new Intl.NumberFormat("en-IN", {
      style: "currency",
      currency: "INR",
      notation: "compact",
      compactDisplay: "long",
      minimumFractionDigits: 2, // 强制至少保留两位小数
      maximumFractionDigits: 2  // 限制最多保留两位小数
    }).format(parseFloat(just_the_number));

console.log(formatted_amount) // 输出 ₹89.73L

说明

  • 两个小数位数参数配合使用,固定结果显示两位小数,避免默认规则下的过度舍入。
  • 显式用parseFloat将字符串转为数值,比直接传字符串更严谨,避免潜在的类型处理问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 05:53:11