diff --git a/lib/OpenLayers/BaseTypes.js b/lib/OpenLayers/BaseTypes.js index b0c96956a7..87617da3c5 100644 --- a/lib/OpenLayers/BaseTypes.js +++ b/lib/OpenLayers/BaseTypes.js @@ -295,7 +295,25 @@ OpenLayers.Number = { str = integer + dsep + rem; } return str; - } + }, + + /** + * Method: zeroPad + * Create a zero padded string optionally with a radix for casting numbers. + * + * Parameters: + * num - {Number} The number to be zero padded. + * len - {Number} The length of the string to be returned. + * radix - {Number} An integer between 2 and 36 specifying the base to use + * for representing numeric values. + */ + zeroPad: function(num, len, radix) { + var str = num.toString(radix || 10); + while (str.length < len) { + str = "0" + str; + } + return str; + } }; /** diff --git a/tests/BaseTypes.html b/tests/BaseTypes.html index cc391003da..045ac65491 100644 --- a/tests/BaseTypes.html +++ b/tests/BaseTypes.html @@ -278,6 +278,17 @@ OpenLayers.Number.decimalSeparator = ","; t.eq(format(num, 3), "12.345,679", "changing thousands/decimal separator globally works"); } + + function test_Number_zeroPad(t) { + t.plan(6); + var pad = OpenLayers.Number.zeroPad; + t.eq(pad(15, 4), "0015", "left padding works"); + t.eq(pad(15, 2), "15", "no left padding when equal to number of digits"); + t.eq(pad(15, 1), "15", "no left padding when less than number of digits"); + t.eq(pad(10, 5, 2), "01010", "radix modified and padding works"); + t.eq(pad(10, 5, 8), "00012", "radix modified and padding works"); + t.eq(pad(10, 5, 36), "0000a", "radix modified and padding works"); + } function test_Function_bind(t) { t.plan(12);