Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PHP

how to convert number into million and billion suffix in PHP using brick/Money package

    private const Million = 'million';
    private const Billion = 'billion';

    public function format(Money $money)
    {
        $million = Money::of(1000000, 'GBP');
        $billion = Money::of(1000000000, 'GBP');

        $formatter = new NumberFormatter('en_GB', NumberFormatter::CURRENCY);

        if ($money->isGreaterThanOrEqualTo($billion)) {
            return $this->formatWithSuffix($money, $billion, self::Billion, $formatter);
        }

        if ($money->isGreaterThanOrEqualTo($million)) {
            return $this->formatWithSuffix($money, $million, self::Million, $formatter);
        }

        $formatter->setAttribute(NumberFormatter::MAX_FRACTION_DIGITS, 0);

        return $money->formatWith($formatter);
    }

    protected function formatWithSuffix(Money $money, Money $scale, string $suffix, $formatter)
    {
        $formatter->setPattern("£#0.## $suffix");

        return $money->dividedBy($scale->getAmount(), RoundingMode::UP)->formatWith($formatter);
    }
 
PREVIOUS NEXT
Tagged: #convert #number #million #billion #suffix #PHP #package
ADD COMMENT
Topic
Name
7+7 =