fork(4) download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.math.*;
  6. import java.io.*;
  7.  
  8. /* Name of the class has to be "Main" only if the class is public. */
  9. class Ideone
  10. {
  11. public static void main (String[] args) throws java.lang.Exception
  12. {
  13. double n = 1234567.8912;
  14.  
  15. System.out.println(getRounded(n, 10));
  16.  
  17. n = 12.345678915;
  18. System.out.println(getRounded(n, 10));
  19.  
  20. n = 0.012347874587456145;
  21. System.out.println(getRounded(n, 10));
  22.  
  23. n = 5;
  24. System.out.println(getRounded(n, 10));
  25. }
  26.  
  27. private static BigDecimal getRounded(double n, int totalDigits) {
  28.  
  29. String nString = Double.toString(n);
  30. if(nString.contains(".")) {
  31. int dotPos = nString.indexOf("."); // = number of digits before the decimal point
  32.  
  33. int remainingDigits = totalDigits - dotPos; // = remaining digits after the decimal point
  34.  
  35. return new BigDecimal(nString).setScale(remainingDigits, BigDecimal.ROUND_HALF_UP); // round
  36. }
  37.  
  38. return new BigDecimal(n);
  39. }
  40. }
Success #stdin #stdout 0.05s 711168KB
stdin
Standard input is empty
stdout
1234567.891
12.34567892
0.012347875
5.000000000