How to round up a number in Javascript?

I want to use Javascript to round up a number. Since the number is currency, I want it to round up like in these examples (2 decimal points):

  • 192.168 => 192.20
  • 192.11 => 192.20
  • 192.21 => 192.30
  • 192.26 => 192.30
  • 192.20 => 192.20

How to achieve this using Javascript? The built-in Javascript function will round up the number based on standard logic (less and more than 5 to round up).


Solution 1:

/**
 * @param num The number to round
 * @param precision The number of decimal places to preserve
 */
function roundUp(num, precision) {
  precision = Math.pow(10, precision)
  return Math.ceil(num * precision) / precision
}

roundUp(192.168, 1) //=> 192.2

Solution 2:

Little late but, can create a reusable javascript function for this purpose:

// Arguments: number to round, number of decimal places
function roundNumber(rnum, rlength) { 
    var newnumber = Math.round(rnum * Math.pow(10, rlength)) / Math.pow(10, rlength);
    return newnumber;
}

Call the function as

alert(roundNumber(192.168,2));

Solution 3:

Normal rounding will work with a small tweak:

Math.round(price * 10)/10

and if you want to keep a currency format, you can use the Number method .toFixed()

(Math.round(price * 10)/10).toFixed(2)

Though this will make it a String =)

Solution 4:

Very near to TheEye answer, but I change a little thing to make it work:

var num = 192.16;
    
console.log(    Math.ceil(num * 10) / 10    );

Solution 5:

The OP expects two things:
A. to round up to the higher tenths, and
B. to show a zero in the hundredths place (a typical need with currency).

Meeting both requirement would seem to necessitate a separate method for each of the above. Here's an approach that builds on suryakiran's suggested answer:

//Arguments: number to round, number of decimal places.

function roundPrice(rnum, rlength) {
    var newnumber = Math.ceil(rnum * Math.pow(10, rlength-1)) / Math.pow(10, rlength-1);
    var toTenths = newnumber.toFixed(rlength);
    return toTenths;
}

alert(roundPrice(678.91011,2)); // returns 679.00
alert(roundPrice(876.54321,2)); // returns 876.60

Important note: this solution produces a very different result with negative and exponential numbers.

For the sake of comparison between this answer and two that are very similar, see the following 2 approaches. The first simply rounds to the nearest hundredth per usual, and the second simply rounds up to the nearest hundredth (larger).

function roundNumber(rnum, rlength) { 
    var newnumber = Math.round(rnum * Math.pow(10, rlength)) / Math.pow(10, rlength);
    return newnumber;
}

alert(roundNumber(678.91011,2)); // returns 678.91

function ceilNumber(rnum, rlength) { 
    var newnumber = Math.ceil(rnum * Math.pow(10, rlength)) / Math.pow(10, rlength);
    return newnumber;
}

alert(ceilNumber(678.91011,2)); // returns 678.92