Freitag, 22. Juni 2012

Easy rounding with Javascript round() wrapper

Really simple method to easily round with javascript:
function round (number, fractionalDigits) {
    "use strict";
    if (!number) {
        return; 
    }
    var multiplicator = 1;
    while (fractionalDigits--) {
        multiplicator *= 10;
    }
    return Math.round(number * multiplicator) / multiplicator;
}

Just pass in the number to round and the number of fractionalDigits you'd like to keep, like:
round(95.12345, 2); will return 95.12
round(95.54555, 4); will return 95.55

If you omit the last param, you'll get no fractionalDigit, like:
round(95.12345); will return 95
round(95.50000); will return 96

One last call: Don't use it as is, create a namespace for it to reside in! 


Or append it to Number, then you can remove the number param. ;)
Number.prototype.round = function(fractionalDigits) {
    "use strict";
    var multiplicator = 1; 
    while (fractionalDigits--) { 
        multiplicator *= 10; 
    } 
    return Math.round(this * multiplicator) / multiplicator;
}

Call it like:
var number = 8.12345;
number.round(2); will return 8.12


Have fun! 

Keine Kommentare:

Kommentar posten