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

General Grievance
  • 4,555
  • 31
  • 31
  • 45
cyberfly
  • 5,568
  • 8
  • 50
  • 67

10 Answers10

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
Andrew Marshall
  • 95,083
  • 20
  • 220
  • 214
  • 2
    @AndrewMarshall what is the purpose of multiplying, then dividing by 10? – codecowboy Jan 07 '13 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. – Andrew Marshall Jan 07 '13 at 23:22
  • 2
    If you get some number like `192.19999999999997`, you can apply `.toFixed(1)` to the `num` – flamer.ohr Mar 08 '16 at 02: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! –  Apr 30 '16 at 10:59
  • This solution has bug: Math.ceil(0.0159 * 1000000000) / precision. You will get a fraction 0.015900001. Need to add a range validation for precision. – Frank Dec 24 '17 at 01:00
  • 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 '20 at 21:28
27

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

Shad
  • 15,134
  • 2
  • 22
  • 34
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));
Ryan Endacott
  • 8,772
  • 4
  • 27
  • 39
suryakiran
  • 1,976
  • 25
  • 41
  • 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 04 '16 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 01 '17 at 04: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    );
vsync
  • 118,978
  • 58
  • 307
  • 400
Hoàng Long
  • 10,746
  • 20
  • 75
  • 124
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
Kay V
  • 3,738
  • 2
  • 20
  • 20
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.

zhulien
  • 5,145
  • 3
  • 22
  • 36
John Grabauskas
  • 310
  • 2
  • 5
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));
}
Behnam
  • 6,244
  • 1
  • 39
  • 36
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

Nicolas BADIA
  • 5,612
  • 7
  • 43
  • 46
  • 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. – Andrew Marshall Dec 10 '17 at 22:07
  • @AndrewMarshall have reason, your expected values are wrong for case 2 and 3. – Amn Jan 22 '20 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
General Grievance
  • 4,555
  • 31
  • 31
  • 45
Divyesh
  • 121
  • 1
  • 7
-4

parseInt always rounds down soo.....

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

do parseInt()+1

Omar
  • 2,726
  • 2
  • 32
  • 65
  • ...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. – General Grievance Mar 21 '23 at 12:34