Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 699
dojie Avatar asked Jan 18 '26 23:01

dojie


1 Answers

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.

like image 147
Christian Phillips Avatar answered Jan 20 '26 16:01

Christian Phillips



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!