Friday, September 02, 2011

Servoy TIP: 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!

2 comments:

Greg Pierce said...

Great tip. You can also try extending the Number prototype with this functionality.

Number.prototype.suffix = function() {
//your function to return just the suffix
}

Number.prototype.withSuffix = function() {
// your function to return the whole string
}

Run that somewhere in your solution startup/init process, then all numbers will know how to return their suffix:

(1).suffix(); // "st"
(2).withSuffix(); // "2nd"

var n = 10;
n.suffix(); // "th"

Bob Cusick said...

AWESOME, Greg! Thanks very much for this!

Web Analytics