September 1, 2009

ActionScript 3: Adding a textual suffix to numbers

If you need to write out a number with a textual suffix, like "25th" or "173rd", there's a little logic that will make this really easy. Check it out:

// suffixes corresponding to the last digit of a number: 0-9
private static const NUMBER_SUFFIXES:Array = [ 'th', 'st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th' ];

private function getNumberSuffix( value : int ) : String
{
// handle most cases by modding by ten
var suffix:String = NUMBER_SUFFIXES[ value % 10 ];
if( value % 100 >= 11 && value % 100 <= 13 ) suffix = 'th'; // handle 11-13
if( value == 0 ) suffix = ''; // handle zero
return suffix;
}

No comments:

Post a Comment