dojie
dojie

Reputation: 33

Convert an ordinal string to an integer with icu4j

I am attempting to convert an ordinal string, say "FOURTH" to integer 4. How can I accomplish this with the International Components for Unicode library for Java, icu4j?

RuleBasedNumberFormat formatter = new RuleBasedNumberFormat(Locale.US, RuleBasedNumberFormat.ORDINAL);

return formatter.parse("FOURTH").intValue();

Seems like this is not working, as 0 is being returned. I'm expecting this to return 4.

Any help would be appreciated. Thank you.

Upvotes: 3

Views: 281

Answers (1)

Christian Phillips
Christian Phillips

Reputation: 84

So I read up on the Javadoc documentation of icu4j and the RuleBasedNumberFormat does not have FOURTH as a parsable string although it does support four. And instead of using RuleBasedNumberFormat.ORDINAL uses RuleBasedNumberFormat.SPELLOUT.

RuleBasedNumberFormat formatter = new RuleBasedNumberFormat( Locale.US , RuleBasedNumberFormat.SPELLOUT );
try
{
    int result = formatter.parse( "FOURTH".toLowerCase( Locale.ROOT ) ).intValue();
    System.out.println( "result = " + result );
}
catch ( ParseException e )
{
    … add code to handle exception.
}

When run:

4

This is what the code should look like and make sure to use .toLowerCase(Locale.ROOT) because parse does not work on upperCase strings.

Upvotes: 3

Related Questions