scriptfusion/byte-formatter

将字节数值格式化为可读字符串。

4.1.1 2022-12-13 03:14 UTC

This package is auto-updated.

Last update: 2024-09-14 18:26:24 UTC


README

Latest version Total downloads Build status Test coverage Code style

ByteFormatter 将字节数值格式化为可读字符串。自动计算适当的指数,确保值不超过基数。例如,在基数 1024 中,format(1023) 返回 1023 B,但 format(1024) 返回 1 KiB 而不是 1024 B

用法

默认情况下,字节按 Base::BINARY 划分为 1024 的倍数。

(new ByteFormatter)->format(0x80000);

512 KiB

可以通过指定 Base::DECIMAL 作为基数,将字节划分为 1000 的倍数。

(new ByteFormatter)->setBase(Base::DECIMAL)->format(500000);

500 KB

精度

默认情况下,所有值都四舍五入到最接近的整数。

(new ByteFormatter)->format(0x80233);

513 KiB

使用 setPrecision() 增加默认精度可以允许指定小数点后的数字位数。

(new ByteFormatter)->setPrecision(2)->format(0x80233);

512.55 KiB

增加精度会增加允许的最大数字位数,但格式化器只会显示所需的数字。

(new ByteFormatter)->setPrecision(2)->format(0x80200);

512.5 KiB

如果不需要这种行为,可以禁用自动精度缩放。

(new ByteFormatter)->setPrecision(2)->disableAutomaticPrecision()->format(0x80200);

512.50 KiB

可以通过将第二个参数传递给 format() 来覆盖默认精度。

(new ByteFormatter)->setPrecision(2)->format(0x80233, 4);

512.5498 KiB

输出格式

可以通过调用 setFormat() 来更改格式,该函数接受一个字符串格式参数。默认格式为 '%v %u'。格式字符串中的 %v%u 将分别替换为计算出的 单位

(new ByteFormatter)->setFormat('%v%u')->format(0x80000);

512KiB

固定指数

格式化器的主要优点之一是自动计算适当的指数,但也可以使用 setFixedExponent() 将指数固定为特定值。

(new ByteFormatter)->setFixedExponent(1)->format(1024 * 1024);

1024 KiB

通常我们期望上面的示例输出 1 MiB,但由于指数被锁定为 1,输出始终为 KiB。请参阅以下表格,了解指数如何映射到符号。

单位自定义

单位由扩展 UnitDecorator 的装饰器提供。提供了两种实现:默认的 SymbolDecorator 和可选的 NameDecorator

单位装饰器在请求装饰值时接收格式化器的基数,以便可以为不同的基数返回不同的单位。例如,默认装饰器在基数 1024 时输出 KiB(对于 210 < bytes < 220),但在基数 1000 时输出 KB(对于 1000 < bytes < 1000000)。可以通过调用 SymbolDecorator::setSuffix() 并使用所需的 SymbolDecorator 后缀常量来抑制这种行为,以防止单位在更改基数时更改。装饰器还接收指数和缩放字节数值。

符号装饰器

SymbolDecorator 是默认的单位装饰器,返回类似 BKBMB 等的单位。可以使用以下表格中的类常量之一来更改符号的后缀。

以下示例使用基数 1024,但显示像 Windows 资源管理器那样的计量后缀。

(new ByteFormatter(new SymbolDecorator(SymbolDecorator::SUFFIX_METRIC)))
    ->format(0x80000)

512 KB

如果您喜欢简洁的表示,可以使用 SUFFIX_NONE 移除后缀。

(new ByteFormatter(new SymbolDecorator(SymbolDecorator::SUFFIX_NONE)))
    ->format(0x80000)

512 K

请注意,当禁用后缀时,字节不会显示单位。如果不喜欢这种行为,可以使用 SymbolDecorator::alwaysShowUnit() 强制显示字节单位。

(new ByteFormatter(new SymbolDecorator(SymbolDecorator::SUFFIX_NONE)))
    ->format(512)

512

(new ByteFormatter(
    (new SymbolDecorator(SymbolDecorator::SUFFIX_NONE))
        ->alwaysShowUnit()
))
    ->format(512)

512 B

名称装饰器

NameDecorator 可以用来替换默认装饰器,并返回类似 bytekilobytemegabyte 等的单位。

(new ByteFormatter(new NameDecorator))
    ->format(0x80000)

512 kibibytes

使用十进制基数

(new ByteFormatter(new NameDecorator))
    ->setBase(Base::DECIMAL)
    ->format(500000)

500 kilobytes

测试

本库已完全通过单元测试。从命令行运行测试,请使用composer test。本文档中的所有示例都可以在DocumentationTest中找到。