Browse Source

Merge pull request #7339 from ritesh-pandey/issue-7091

Issue #7091 Number Helper - Add Ordinal Number Suffix
Mark Story 10 years ago
parent
commit
8af055e4ee
3 changed files with 52 additions and 0 deletions
  1. 13 0
      src/I18n/Number.php
  2. 11 0
      src/View/Helper/NumberHelper.php
  3. 28 0
      tests/TestCase/I18n/NumberTest.php

+ 13 - 0
src/I18n/Number.php

@@ -312,4 +312,17 @@ class Number
 
         return $formatter;
     }
+
+    /**
+     * Returns a formatted integer as an ordinal number string (e.g. 1st, 2nd, 3rd, 4th, [...])
+     *
+     * @param int|float $value An integer
+     * @return string
+     */
+    public static function ordinal($value)
+    {
+        $locale = I18n::locale();
+        $formatter = new NumberFormatter($locale, NumberFormatter::ORDINAL);
+        return $formatter->format($value);
+    }
 }

+ 11 - 0
src/View/Helper/NumberHelper.php

@@ -230,4 +230,15 @@ class NumberHelper extends Helper
     {
         return [];
     }
+
+    /**
+     * Formats a number into locale specific ordinal suffix.
+     *
+     * @param int|float $value An integer
+     * @return string formatted number
+     */
+    public function ordinal($value)
+    {
+        return $this->_engine->ordinal($value);
+    }
 }

+ 28 - 0
tests/TestCase/I18n/NumberTest.php

@@ -538,4 +538,32 @@ class NumberTest extends TestCase
         $result = $this->Number->toReadableSize(512.05 * 1024 * 1024 * 1024);
         $this->assertEquals('512,05 GB', $result);
     }
+    
+    /**
+     * test ordinal() with locales
+     *
+     * @return void
+     */
+    public function testOrdinal()
+    {
+        I18n::locale('en_US');
+        $result = $this->Number->ordinal(1);
+        $this->assertEquals('1st', $result);
+
+        $result = $this->Number->ordinal(2);
+        $this->assertEquals('2nd', $result);
+
+        $result = $this->Number->ordinal(3);
+        $this->assertEquals('3rd', $result);
+
+        $result = $this->Number->ordinal(4);
+        $this->assertEquals('4th', $result);
+
+        I18n::locale('fr_FR');
+        $result = $this->Number->ordinal(1);
+        $this->assertEquals('1er', $result);
+
+        $result = $this->Number->ordinal(2);
+        $this->assertEquals('2e', $result);
+    }
 }