From ce69912782c730cbeb9147535aaa0d68095d04bf Mon Sep 17 00:00:00 2001 From: euzuro Date: Wed, 26 Jul 2006 12:22:12 +0000 Subject: [PATCH] add limitSigDigs() function to number's prototype. tests included git-svn-id: http://svn.openlayers.org/trunk/openlayers@1008 dc9f47b5-9b13-0410-9fdd-eb0c1a62fdaf --- lib/OpenLayers/Util.js | 16 ++++++++++++++++ tests/test_Util.html | 29 ++++++++++++++++++++++++++++- 2 files changed, 44 insertions(+), 1 deletion(-) diff --git a/lib/OpenLayers/Util.js b/lib/OpenLayers/Util.js index 9b31a90cc1..377a9fa94d 100644 --- a/lib/OpenLayers/Util.js +++ b/lib/OpenLayers/Util.js @@ -707,6 +707,22 @@ Array.prototype.indexOf = function(element) { return index; } +/** + * @param {int} sig + * + * @returns The number, rounded to the specified number of significant digits. + * If null, 0, or negaive value passed in, returns 0 + * @type int + */ +Number.prototype.limitSigDigs = function(sig) { + var number = (sig > 0) ? this.toString() : 0; + if (sig < number.length) { + var exp = number.length - sig; + number = Math.round( this / Math.pow(10, exp)) * Math.pow(10, exp); + } + return parseInt(number); +} + /** * @param {String} id * @param {OpenLayers.Pixel} px diff --git a/tests/test_Util.html b/tests/test_Util.html index e35f7c029e..2d731076b5 100644 --- a/tests/test_Util.html +++ b/tests/test_Util.html @@ -393,7 +393,7 @@ t.eq(uObj[bKey.toUpperCase()], bValue, "new uppercase value present"); } - function test_10_Util_createUniqueID(t) { + function test_11_Util_createUniqueID(t) { t.plan(2); var id = OpenLayers.Util.createUniqueID(); @@ -402,6 +402,33 @@ var id = OpenLayers.Util.createUniqueID("chicken"); t.ok( id.startsWith("chicken"), "OpenLayers.Util.createUniqueID starts id correctly"); } + + function test_12_Util_limitSigDigs(t) { + + t.plan(7); + + var x; + + x = 123456; + t.eq(x.limitSigDigs(3), 123000, "correctly rounds down"); + + x = 555555; + t.eq(x.limitSigDigs(3), 556000, "correctly rounds up"); + + x = 66; + t.eq(x.limitSigDigs(3), 66, "correctly handles number smaller than sigdig"); + + t.eq(x.limitSigDigs(null), 0, "correctly handles null sigdig"); + t.eq(x.limitSigDigs(0), 0, "correctly handles 0 sigdig"); + t.eq(x.limitSigDigs(-1), 0, "correctly handles negative sigdig"); + + x = 0; + t.eq(x.limitSigDigs(2), 0, "correctly handles 0 number"); + + + + } + // -->