179

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).

0

10 Answers 10

332
/**
 * @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
6
  • 2
    @AndrewMarshall what is the purpose of multiplying, then dividing by 10?
    – codecowboy
    Jan 7, 2013 at 18:23
  • 7
    @codecowboy If you don't, then ceil() will give you 193, so we must ensure that all the precision we want to keep is before the decimal point. Then we do the inverse operation in order to restore the “original” value. Jan 7, 2013 at 23:22
  • 2
    If you get some number like 192.19999999999997, you can apply .toFixed(1) to the num
    – flamer.ohr
    Mar 8, 2016 at 2:37
  • 8
    And for those here wondering how to round up to the nearest WHOLE number, you just need Math.ceil(). The rest is just to deal with decimals. To save others the time it took my brain to get to that!
    – user2493235
    Apr 30, 2016 at 10:59
  • 1
    BEWARE THIS FUNCTION IS NOT COMPLETELY ACCURATE! roundUp(1.09, 2) returns 1.1 which is wrong! The expected answer is 1.09 still.
    – Samer
    May 12, 2020 at 21:28
28

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 =)

4
  • Math.round(192.11 * 100)/100 -> 192.11
    – krtek
    Mar 4, 2011 at 7:57
  • 1
    The second one needs no rounding, it's more like price.toFixed(2) Mar 4, 2011 at 7:58
  • @Krtek ooops, Thanks for catching that. I mis-read the question. Answer updated.
    – Shad
    Mar 4, 2011 at 7:59
  • 3
    The OP asked how to round up a number, so Math.ceil should be used here instead of Math.round.
    – kloddant
    Apr 4, 2016 at 13:38
27

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));
2
  • 2
    This works great, but the OP asked how to round up a number, so Math.ceil should be used here instead of Math.round.
    – kloddant
    Apr 4, 2016 at 14:02
  • This answer is better than the accepted answer if you're looking to round up properly despite which decimal place you're aiming for. Ex: 1.054 --> 1.05 1.055 --> 1.06 HOWEVER here is an edge case: 1.005 --> 1 1.006 --> 1.01 AND 1.015 --> 1.01 1.016 --> 1.02 So be careful.
    – Jay K
    Mar 1, 2017 at 4:41
12

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    );

0
2

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
2

ok, this has been answered, but I thought you might like to see my answer that calls the math.pow() function once. I guess I like keeping things DRY.

function roundIt(num, precision) {
    var rounder = Math.pow(10, precision);
    return (Math.round(num * rounder) / rounder).toFixed(precision)
};

It kind of puts it all together. Replace Math.round() with Math.ceil() to round-up instead of rounding-off, which is what the OP wanted.

1

this function limit decimal without round number

function limitDecimal(num,decimal){
     return num.toString().substring(0, num.toString().indexOf('.')) + (num.toString().substr(num.toString().indexOf('.'), decimal+1));
}
2
  • As shorter alternative: return ( '' + num ).split('.').shift()
    – Yogi
    Nov 27, 2015 at 20:49
  • thanks Roberto this code work, but remove all decimal
    – Behnam
    Nov 29, 2015 at 7:31
0

I've been using @AndrewMarshall answer for a long time, but found some edge cases. The following tests doesn't pass:

equals(roundUp(9.69545, 4), 9.6955);
equals(roundUp(37.760000000000005, 4), 37.76);
equals(roundUp(5.83333333, 4), 5.8333);

Here is what I now use to have round up behave correctly:

// Closure
(function() {
  /**
   * Decimal adjustment of a number.
   *
   * @param {String}  type  The type of adjustment.
   * @param {Number}  value The number.
   * @param {Integer} exp   The exponent (the 10 logarithm of the adjustment base).
   * @returns {Number} The adjusted value.
   */
  function decimalAdjust(type, value, exp) {
    // If the exp is undefined or zero...
    if (typeof exp === 'undefined' || +exp === 0) {
      return Math[type](value);
    }
    value = +value;
    exp = +exp;
    // If the value is not a number or the exp is not an integer...
    if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) {
      return NaN;
    }
    // If the value is negative...
    if (value < 0) {
      return -decimalAdjust(type, -value, exp);
    }
    // Shift
    value = value.toString().split('e');
    value = Math[type](+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp)));
    // Shift back
    value = value.toString().split('e');
    return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp));
  }

  // Decimal round
  if (!Math.round10) {
    Math.round10 = function(value, exp) {
      return decimalAdjust('round', value, exp);
    };
  }
  // Decimal floor
  if (!Math.floor10) {
    Math.floor10 = function(value, exp) {
      return decimalAdjust('floor', value, exp);
    };
  }
  // Decimal ceil
  if (!Math.ceil10) {
    Math.ceil10 = function(value, exp) {
      return decimalAdjust('ceil', value, exp);
    };
  }
})();

// Round
Math.round10(55.55, -1);   // 55.6
Math.round10(55.549, -1);  // 55.5
Math.round10(55, 1);       // 60
Math.round10(54.9, 1);     // 50
Math.round10(-55.55, -1);  // -55.5
Math.round10(-55.551, -1); // -55.6
Math.round10(-55, 1);      // -50
Math.round10(-55.1, 1);    // -60
Math.round10(1.005, -2);   // 1.01 -- compare this with Math.round(1.005*100)/100 above
Math.round10(-1.005, -2);  // -1.01
// Floor
Math.floor10(55.59, -1);   // 55.5
Math.floor10(59, 1);       // 50
Math.floor10(-55.51, -1);  // -55.6
Math.floor10(-51, 1);      // -60
// Ceil
Math.ceil10(55.51, -1);    // 55.6
Math.ceil10(51, 1);        // 60
Math.ceil10(-55.59, -1);   // -55.5
Math.ceil10(-59, 1);       // -50

Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round

2
  • 1
    Your test cases seem incorrect. roundUp(37.760000000000005, 4) should be 37.7601, and roundUp(5.83333333, 4) should be 5.8334. These two (and your first) all hold true for the fn I provided. Dec 10, 2017 at 22:07
  • @AndrewMarshall have reason, your expected values are wrong for case 2 and 3.
    – Amn
    Jan 22, 2020 at 13:58
0

Here simplest way to roundup your value in javascript

let num = 5.56789;
let n = num.toFixed(2);
console.log(n); //output 5.57

1
  • The question asks for a precision of 1 decimal point. i.e. 5.56 -> 5.6. But also, toFixed does not round up. Mar 21 at 12:37
-4

parseInt always rounds down soo.....

console.log(parseInt(5.8)+1);

do parseInt()+1

1
  • ...Unless you give it an integer. In this case 5 rounds to 6. Also, the question asks about rounding up to a precision of 1 decimal point. Mar 21 at 12:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.