Skip to content

Commit

Permalink
Add option second argument to abbreviate to round off decimals
Browse files Browse the repository at this point in the history
  • Loading branch information
andrewjmead committed Jun 6, 2023
1 parent 7384ba1 commit 6ca046a
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 4 deletions.
7 changes: 5 additions & 2 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ A dependency-free set of classes you may find useful for WordPress development.
* [Periodic](#periodic)
* [::check($option_name, $date_interval): bool](#periodic)
* [Number](#number)
* [::abbreviate($number): string](#abbreviate)
* [::abbreviate($number, bool $round = false): string](#abbreviate)
* [Timezone](#timezone)
* [::site_timezone(): DateTimeZone](#site_timezone)
* [::site_offset(): string](#site_offset)
Expand Down Expand Up @@ -72,7 +72,7 @@ Calls to `check` will always return a boolean value. The value will be `true` if

### Abbreviate

**Number::abbreviate(int|float $number): string**
**Number::abbreviate(int|float $number, bool $round = false): string**

The `abbreviate` methods abbreviates large numbers such as `742898` into shorter strings such as `743K`.

Expand All @@ -84,6 +84,9 @@ use Proper\Number;
Number::abbreviate(1260000); // 1.3M

Number::abbreviate(133800); // 133.8K

// Round off decimals
Number::abbreviate(133800, true); // 134K
```

It provides abbreviations for:
Expand Down
4 changes: 2 additions & 2 deletions source/Number.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ class Number
*
* @return string
*/
public static function abbreviate($number): string
public static function abbreviate($number, $round = false): string
{
$number = (int) $number;
$abbreviations = [
Expand All @@ -24,7 +24,7 @@ public static function abbreviate($number): string
$upper_range = $abbreviation_value * 1000;

if ($number < $upper_range) {
$decimals = $number < 1000 ? 0 : 1;
$decimals = $number < 1000 || $round ? 0 : 1;
$result = $number / $abbreviation_value;
$result = number_format_i18n($result, $decimals) . $abbreviation;

Expand Down
16 changes: 16 additions & 0 deletions tests/NumberTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,22 @@ public function test_thousands()
$this->assertEquals($expected, $actual);
}

public function test_rounding_option_down()
{
$actual = Number::abbreviate(133300, true);
$expected = '133K';

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

public function test_rounding_option_up()
{
$actual = Number::abbreviate(133800, true);
$expected = '134K';

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

public function test_billions()
{
$actual = Number::abbreviate(999000000000);
Expand Down

0 comments on commit 6ca046a

Please sign in to comment.