0

I want to round off a value for ex:

12.166666 ----> 12.00

12.49999 ----> 12.00

12.5111 ----> 13.00

12.9999 ----> 13.00

I want to to round off wrt 50 paise.

gsamaras
  • 71,951
  • 46
  • 188
  • 305
sgrgmngt
  • 907
  • 3
  • 12
  • 15
  • 5
    [Google](https://www.google.com/search?q=round+a+number+in+javascript&sugexp=chrome,mod=4&sourceid=chrome&ie=UTF-8) is your friend. –  Aug 30 '12 at 06:13
  • check http://stackoverflow.com/questions/9902968/why-does-math-round0-49999999999999994-return-1 – Nandkumar Tekale Aug 30 '12 at 06:13

2 Answers2

9

You can take a look at the Math.round(double a) method.

System.out.println(Math.round(12.51));//Yields 13
System.out.println(Math.round(12.49));//Yields 12
System.out.println(Math.round(12.50));//Yields 13
npinti
  • 51,780
  • 5
  • 72
  • 96
  • This can lead to [surprises](http://stackoverflow.com/questions/9902968/why-does-math-round0-49999999999999994-return-1?lq=1) sometimes. – Jesper Aug 30 '12 at 07:37
  • @Jesper: Very interesting. According to the [bug report](http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6430675) though it has been fixed in Java 7. Although I do not know what version is the OP running, he/she could always upgrade their environment to go around this problem. – npinti Aug 30 '12 at 07:50
  • I just want to know why System.out.println(Math.round(12.49));//Yields 12 become 12? It also should become 13. Why its happen – Milinda Bandara Mar 13 '14 at 06:41
  • @MilindaBandara: Anything less than 12.5 will be rounded down to 12. That being said, the `Math.ceil(double a)` method will yield the next largest integer. – npinti Mar 13 '14 at 06:52
0

You can use Math.round . For documentation take a look at: http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html#round(double)

Afshin Moazami
  • 2,092
  • 5
  • 33
  • 55
Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217