Skip to content

Commit

Permalink
Add support for internationalized abbreviations
Browse files Browse the repository at this point in the history
  • Loading branch information
andrewjmead committed May 30, 2023
1 parent 2614da3 commit 3eb585c
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 4 deletions.
4 changes: 2 additions & 2 deletions source/Number.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ static public function abbreviate( $number ): string {
if ( $number < $upper_range ) {
$decimals = $number < 1000 ? 0 : 1;
$result = $number / $abbreviation_value;
$result = number_format( $result, $decimals ) . $abbreviation;
$result = number_format_i18n( $result, $decimals ) . $abbreviation;

// Strip out decimals that are 0 so 1.0T becomes 1T
$result = strpos( $result, '.0' ) === false ? $result : str_replace( '.0', '', $result );
Expand All @@ -34,6 +34,6 @@ static public function abbreviate( $number ): string {
}

// Do nothing for numbers past the trillions
return (string) $number;
return number_format_i18n($number, 0);
}
}
30 changes: 28 additions & 2 deletions tests/NumberTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,13 @@
* Tests for Number
*/
class NumberTest extends \WP_UnitTestCase {
protected function setUp(): void {
switch_to_locale( 'en_US' );
}

public static function tearDownAfterClass(): void {
switch_to_locale( 'en_US' );
}

public function test_small_numbers() {
$actual = Number::abbreviate( 1 );
Expand Down Expand Up @@ -56,9 +63,28 @@ public function test_rounding_down() {
$this->assertEquals( $expected, $actual );
}

public function test_abbreviations_are_internationalized() {
switch_to_locale( 'de_DE' );
$actual = Number::abbreviate( 1200 );
$expected = '1,2K';

$this->assertEquals( $expected, $actual );
}

public function test_do_nothing_past_trillions() {
$actual = Number::abbreviate(1000000000000000);
$expected = '1000000000000000';
// setlocale works with number_format which is from php
// switch_to_locale is wp and works with number_format_i18n which is also wordprsss

$actual = Number::abbreviate( 1000000000000000 );
$expected = '1,000,000,000,000,000';

$this->assertEquals( $expected, $actual );
}

public function test_values_past_trillions_are_internationalized() {
switch_to_locale( 'de_DE' );
$actual = Number::abbreviate( 1000000000000000 );
$expected = '1.000.000.000.000.000';

$this->assertEquals( $expected, $actual );
}
Expand Down

0 comments on commit 3eb585c

Please sign in to comment.