Display number as Ordinal number in 'word form' with NumberFormatter PHP class?
Asked Answered
D

1

5

If I'd like to display a given number as ordinal number, I'd do it like this:

<?php
    // Needs 'php5-intl' package to be installed on Debian/Ubuntu

    $set_format = numfmt_create( 'en_US', NumberFormatter::ORDINAL );

    // '3' is displayed as '3rd'
    echo numfmt_format( $set_format, 3 );

?>

But if I'd like to display a given number as ordinal number in word form (e.g. first, second, third, etc.) using a built-in PHP function/class like NumberFormatter, how do I do that? Is it possible?

Related Links:

Demogorgon answered 16/10, 2013 at 17:3 Comment(0)
N
24

You want to be using the SPELLOUT format style, rather thanORDINAL.

The next problem is how to tell the formatter to use the particular ruleset that you are interested in; namely %spellout-ordinal. This can be done by using setTextAttribute().

Example

$formatter = new NumberFormatter('en_US', NumberFormatter::SPELLOUT);
$formatter->setTextAttribute(NumberFormatter::DEFAULT_RULESET,
                             "%spellout-ordinal");

for ($i = 1; $i <= 5; $i++) {
    echo $formatter->format($i) . PHP_EOL;
}

Output

first
second
third
fourth
fifth
Neurosis answered 16/10, 2013 at 19:23 Comment(3)
Do you know how I can get the first letter capitalized (First, Second, Third...)? I mean do I need to use something like ucfirst() or is there a built-in way?Demogorgon
ucfirst() would be okay, I'd assume.Neurosis
Does that support Non-English languages? I'm trying Arabic but still return the usual SPELLOUTClammy

© 2022 - 2024 — McMap. All rights reserved.