Skip to main content

JavaScript function to round to the nearest whole number.

/*!
 * Round to the nearest whole number
 *
 * Article: https://gomakethings.com/refactoring-vanilla-js-code-to-be-more-dry/
 * Source: https://github.com/cferdinandi/vanilla-js-toolkit/blob/master/content/helpers/round.md
 *
 * (c) 2019 Chris Ferdinandi, MIT License
 * https://gomakethings.com
 *
 * @param  {Number|String} num       The numer to round
 * @param  {Number}        precision The whole number to round to (ex. 10, 100, 1000)
 * @param  {String}        method    The rounding method (up, down, or auto - defaults to auto) [optional]
 * @return {String}                  The rounded, delimited number
 */
var round = function(num, precision, method) {
    // Convert string numbers to a float
    num = parseFloat(num);

    // If there's no rounding precision, return the number
    if (!precision) return num.toLocaleString();

    // Possible methods and their values
    var methods = {
        auto: "round",
        up: "ceil",
        down: "floor"
    };

    // Get the method function
    var fn = methods[method];
    if (!fn) {
        fn = "round";
    }

    // Do math!
    return (Math[fn](num / precision) * precision).toLocaleString();
};