Search code examples
phpmultilingualgettext

PHP plural gettext with formatted numbers


I want to be able to format a (multilingual) sentence like:

I have 12,345 widgets.

In my .po I have

msgid "I only have %d widget."
msgid_plural "I have %d widgets."
msgstr[0] "I don't have any widgets."
msgstr[1] "I only have %d widget."
msgstr[2] "I have %d widgets."

ngettext("I only have %d widget.", "I have %d widgets.", 12345);

If I use number_format(12345) I get back a string of "12,345", which can't be used to detect plurals (the docs say that it must be an int).

Is there a way I can have the gettext serve up a formatted number?


Solution

  • You can use sprintf in combination with number_format like:

    sprintf(ngettext("I only have %s widget.", "I have %s widgets.", 1), number_format(1, 0, '.', ','));
    sprintf(ngettext("I only have %s widget.", "I have %s widgets.", 999), number_format(999, 0, '.', ','));
    sprintf(ngettext("I only have %s widget.", "I have %s widgets.", 1000), number_format(1000, 0, '.', ','));
    

    This will return:

    I only have 1 widget.
    I have 999 widgets.
    I have 1,000 widgets.