fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6. import java.math.BigDecimal;
  7. import java.math.RoundingMode;
  8.  
  9. /* Name of the class has to be "Main" only if the class is public. */
  10. class Ideone
  11. {
  12. public static void main (String[] args) throws java.lang.Exception
  13. {
  14. int position;
  15. BigDecimal[] numbers = {new BigDecimal("12345.0"), new BigDecimal("1234567.0"),
  16. new BigDecimal("0.12345"), new BigDecimal("0.1"),
  17. new BigDecimal("0.0012345"), new BigDecimal("123.5"), new BigDecimal("12.5"),
  18. new BigDecimal("1234500000.0000000012345")};
  19.  
  20. for (BigDecimal number : numbers) {
  21. System.out.println(number);
  22. String leftPart = String.valueOf(number).replaceAll("^(\\d+)\\.\\d+", "$1");
  23. String rightPart = String.valueOf(number).replaceAll("^\\d+\\.(\\d+)", "$1");
  24. int left = leftPart.length();
  25. int right = rightPart.length();
  26. if (Integer.parseInt(leftPart) == 0) {
  27. position = 6 + rightPart.replaceAll("^([0]*).*", "$1").length();
  28. } else {
  29. position = 5;
  30. }
  31. if (left <= position) {
  32. number = number.add(new BigDecimal(Math.pow(0.1, position - left)));
  33. } else {
  34. number = number.add(new BigDecimal(Math.pow(10, left - position)));
  35. }
  36. System.out.println(number.setScale(right > 5 ? right : 5, RoundingMode.DOWN) + "\n..................................");
  37. }
  38. }
  39. }
Success #stdin #stdout 0.05s 4386816KB
stdin
Standard input is empty
stdout
12345.0
12346.00000
..................................
1234567.0
1234667.00000
..................................
0.12345
0.12346
..................................
0.1
0.10001
..................................
0.0012345
0.0012346
..................................
123.5
123.51000
..................................
12.5
12.50100
..................................
1234500000.0000000012345
1234600000.0000000012345
..................................