Php 使用 NumberFormatter 最小化大数字,至少包含 2 位整数

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

我正在使用

NumberFormatter
类来格式化和缩小大数字,因为它允许我根据我的语言环境进行翻译和格式化,而无需手动设置所有规则或千步、小数字符等...

123456必须变成123K,123456789123必须变成123B,等等...(到目前为止正常行为)但是,我不希望1234567891234变成1T,而是1,234B。
更一般地说,我希望缩小数字的整数部分始终至少有两位数。

我该怎么做?

php number-formatting
1个回答
0
投票

自定义逻辑需要自定义实现。例如:

<?php

declare(strict_types=1);

class RoughNumberFormatter
{
    private array $symbols = ['', 'K', 'M', 'B', 'T'];
    private array $map = [];
    private int $diff;

    public function __construct(int $minChunk = 2) {
        $this->diff = 10 ** ($minChunk - 1);

        foreach ($this->symbols as $index => $symbol) {
            $this->map[$symbol] = 1000 ** $index;
        }
        $this->map = array_reverse($this->map, true);
    }

    public function handle(int $number): string
    {
        foreach ($this->map as $symbol => $dimension) {
            if ($number >= $dimension * $this->diff) {
                return number_format((int)($number / $dimension)) . $symbol;
            }
        }

        return number_format($number);
    }
}


public function test_dimension_number_formatter(): void
    {
        $formatter = new RoughNumberFormatter();
        $this->assertEquals('0', $formatter->handle(0));
        $this->assertEquals('123', $formatter->handle(123));
        $this->assertEquals('123K', $formatter->handle(123456));
        $this->assertEquals('123B', $formatter->handle(123456789123));
        $this->assertEquals('1,234B', $formatter->handle(1234567891234));
        $this->assertEquals('12T', $formatter->handle(12345678912345));
    }
© www.soinside.com 2019 - 2024. All rights reserved.