Friday, September 2, 2011

Servoy TIP: How To Create a Number Suffix

Here's a tip for adding the number suffix - like 1st, 2nd, 3rd, 4th, etc:

/**
 * @param {Number} input - the number to get the suffix for
 * @param {Number} returnWholeString - values: 0 (or null) - just the suffix, 1 (or >0) - number and suffix
 */
function getNumberSuffix(input,returnWholeString) {
if(returnWholeString == null || returnWholeString == undefined || returnWholeString == 0) {
returnWholeString = 0;
} else {
returnWholeString = 1;
}

var output = "th"
var last = 0;

if(input%100 >= 11 && input%100 <= 13) {
output = "th"
} else {
last = Math.ceil(input%10);
if(last == 1) {
 output = "st";
} else if(last == 2) {
output = "nd";
} else if(last == 3) {
output = "rd";
}
}

if(returnWholeString) {
return input + output;
} else {
return output;
}
}

Example usage:

getNumberSuffix(21) returns "st"
getNumberSuffix(21,1) returns "21st"

getNumberSuffix(13) returns "th"
getNumberSuffix(13,1) returns "13th"


Pretty simple - but powerful!

No comments:

Post a Comment