Skip to content

Instantly share code, notes, and snippets.

@shabeer-dev
Forked from PovilasKorop/index.php
Created March 5, 2022 04:54
Show Gist options
  • Save shabeer-dev/2ec22c1b8742d86d2a77da96a4893f8f to your computer and use it in GitHub Desktop.
Save shabeer-dev/2ec22c1b8742d86d2a77da96a4893f8f to your computer and use it in GitHub Desktop.

Revisions

  1. @PovilasKorop PovilasKorop created this gist Feb 14, 2022.
    73 changes: 73 additions & 0 deletions index.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,73 @@
    <?php

    function getFormattedNumber(
    $value,
    $locale = 'en_US',
    $style = NumberFormatter::DECIMAL,
    $precision = 2,
    $groupingUsed = true,
    $currencyCode = 'USD',
    ) {
    $formatter = new NumberFormatter($locale, $style);
    $formatter->setAttribute(NumberFormatter::FRACTION_DIGITS, $precision);
    $formatter->setAttribute(NumberFormatter::GROUPING_USED, $groupingUsed);
    if ($style == NumberFormatter::CURRENCY) {
    $formatter->setTextAttribute(NumberFormatter::CURRENCY_CODE, $currencyCode);
    }

    return $formatter->format($value);
    }

    echo getFormattedNumber(12345678.9);
    echo '<br />';

    echo getFormattedNumber(
    value: 12345678.9,
    locale: 'pt_BR'
    );
    echo '<br />';

    echo getFormattedNumber(
    value: 12345678.9,
    locale: 'fr_FR'
    );
    echo '<br />';

    echo getFormattedNumber(
    value: 12345678.90,
    precision: 1
    );

    echo '<br />';
    echo getFormattedNumber(
    value: 12345678.90,
    groupingUsed: false
    );

    echo '<br />';
    echo getFormattedNumber(
    value: 12345678.90,
    locale: 'fr_FR',
    style: NumberFormatter::CURRENCY,
    currencyCode: 'EUR',
    );

    echo '<br />';
    echo getFormattedNumber(
    value: 12345678,
    style: NumberFormatter::PADDING_POSITION,
    precision: 3
    );
    echo '<br />';

    echo getFormattedNumber(
    value: 12345678,
    style: NumberFormatter::SPELLOUT
    );
    echo '<br />';

    echo getFormattedNumber(
    value: 0.123,
    style: NumberFormatter::PERCENT,
    precision: 1
    );