2

I have a value like 1724.1000000000001,How can I round up values like such to 1724.11 in javascript? I need a generic function.Please help...

Neji
  • 6,591
  • 5
  • 43
  • 66
user1495475
  • 1,037
  • 3
  • 20
  • 34
  • 1
    possible duplicate of [How to round up a number in Javascript?](http://stackoverflow.com/questions/5191088/how-to-round-up-a-number-in-javascript) and [Round up to 2 decimal places in javascript](http://stackoverflow.com/questions/11832914/round-up-to-2-decimal-places-in-javascript) and [many more](http://stackoverflow.com/search?q=javascript+round+number). – Felix Kling Jan 03 '13 at 11:04
  • So, do you want to round the numbers? So, `17.10001 --> 17.10`, or `17.10001 --> 17.11`? – Cerbrus Jan 03 '13 at 11:14

5 Answers5

5

An easy way to do this is:

var num = 1724.1000000000001;
num = Math.ceil(num * 100) / 100;
alert(num); //  1724.11

How it works:

Ceil will round the value up. But you want to have 2 decimal numbers. The best way to do this is to:

  1. Multiply the value with 100,
  2. Round it up,
  3. Divide it with 100.

Now you have an up rounded value with 2 decimals. This is what happens:

1724.1000000000001 * 100 = 172410.00000000001
round-up on 172410.00000000001 = 172411
172411 / 100 = 1724.11
Laurence
  • 1,815
  • 4
  • 22
  • 35
3

Since the example in the questions asks for a result of 1724.11 instead of 1724.1 I would assume you don't strictly want round, but rather ceil:

var n = 1724.10000000001;
Math.ceil(n * 100) / 100; // >> 1724.11

If a simple round up to the second decimal is required us Math.round instead of Math.ceil.

Emil Ivanov
  • 37,300
  • 12
  • 75
  • 90
1

From http://www.javascriptkit.com/javatutors/round.shtml:

var original=28.453

1) //round "original" to two decimals
var result=Math.round(original*100)/100  //returns 28.45

2) // round "original" to 1 decimal
var result=Math.round(original*10)/10  //returns 28.5

3) //round 8.111111 to 3 decimals
var result=Math.round(8.111111*1000)/1000  //returns 8.111
Andrew Hall
  • 3,058
  • 21
  • 30
1

you can try toFixed to fix to 2 decimals, below is the code.

var num=1724.1999;
alert(num.toFixed(2));​

result 1724.20

0

To round a number to 2 decimals:

var num = 1724.1000000000001;
num = Math.ceil(num*100)/100;

// num == 1724.11

Or, try this:

var num = 1724.1000000000001;
function round(num, decimals){
    var d = Math.pow(10,decimals)
    return Math.ceil(num*d)/d;
}

console.log(round(num,0))
console.log(round(num,1))
console.log(round(num,2))
console.log(round(num,3))
console.log(round(num,4))
// 1725
// 1724.2
// 1724.11
// 1724.101
// 1724.1001
Cerbrus
  • 70,800
  • 18
  • 132
  • 147