为什么 Intl.NumberFormat 将 1000000000 字节格式化为 1BB 而不是 1GB?

问题描述 投票:0回答:2

我正在尝试配置我的

Intl.NumberFormat
实例以显示大量的适当单位,但似乎它显示
B
而不是
G
表示 1000000000,例如1BB/秒而不是 1GB/秒。

这是我的例子:

const rateFormatter = Intl.NumberFormat('en', {
    style: 'unit',
    unit: 'byte-per-second',
    unitDisplay: 'narrow',
    notation: 'compact',
    maximumFractionDigits: 2,
  })
  
 console.log(rateFormatter.format("1000000000"));

为什么会这样?我的浏览器是 MacOS 上最新的 Chrome。

javascript formatting numbers
2个回答
2
投票

这里有一个解决方法,可以检查数字的大小并选择合适的单位。

const bandwidth = (bytespersec) => {
   let units = "byte-per-second";
   let divisor = 1;
   if (bytespersec >= 1e9) {
     units = "gigabyte-per-second";
     divisor = 1e9;
   } else if (bytespersec >= 1e6) {
     units = "megabyte-per-second";
     divisor = 1e6;
   } else if (bytespersec >= 1e3) {
     units = "kilobyte-per-second";
     divisor = 1e3;
   }
   // etc, add more if needed.  Be sure to put the largest unit first in the above if (or re-do the logic)
   
   let f = Intl.NumberFormat('en', {
      style: 'unit',
      unit: units,
      unitDisplay: 'short',
      notation: 'compact',
      maximumFractionDigits: 2,
   });
   
   return f.format(bytespersec / divisor);
 };
 
 console.log(bandwidth(1));
 console.log(bandwidth(1025));
 console.log(bandwidth(1234567));
 console.log(bandwidth(234567890));
 console.log(bandwidth(2000000000));


0
投票

问题似乎出在

Intl
本身。

因为您问题中的代码会产生

1BB/s

如果将

unitDisplay
更改为
long
,您将在控制台中看到
"1B bytes per second"
,例如

const rateFormatter = Intl.NumberFormat('en', {
    style: 'unit',
    unit: 'byte-per-second',
    unitDisplay: 'long',
    notation: 'compact',
    maximumFractionDigits: 2,
  })
  
 console.log(rateFormatter.format("1000000000"));

意味着问题出在

format
函数

测试1

经过一些测试。

我发现了。

传递值

1000000000
输出是
"1B bytes per second"
(您最初根据问题传入)

100000000
输出为
"100M bytes per second"

如果我们将

unitDisplay
改回
narrow

测试2

如果我们再次运行相同的测试,我们会得到

传递值

1000000000
输出是
"1BB/s"
(您最初根据问题传入)

100000000
输出为
"100MB/s"

解决方案

问题是

B
指的是
billion
,所以输出是正确的,但在长单位显示设置中它没有给出
billion bytes per second
,所以它没有损坏,而是实施得很糟糕,值太大了简单只是使用 1B 表示 10 亿

© www.soinside.com 2019 - 2024. All rights reserved.