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.text.*;
  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. System.out.println(format(0.4999d, 1));
  14. System.out.println(format(0.0299d, 2));
  15. System.out.println(format(0.34943d, 3));
  16. System.out.println(format(0.98499d, 3));
  17. System.out.println(format(0.66666666d, 5));
  18.  
  19. System.out.println("---------");
  20.  
  21. // briancherron - Standard method
  22.  
  23. NumberFormat nf = NumberFormat.getInstance();
  24. nf.setMaximumIntegerDigits(0);
  25.  
  26. System.out.println(nf.format(0.4999d));
  27. System.out.println(nf.format(0.0299d));
  28. System.out.println(nf.format(0.34943d));
  29. System.out.println(nf.format(0.98499d));
  30. nf.setMaximumFractionDigits(5);
  31. System.out.println(nf.format(0.66666666d));
  32.  
  33. }
  34.  
  35. public static String format(double value, int decimalPlaces) {
  36. if (value >= 1 || value < 0) {
  37. throw new IllegalArgumentException("Value must be between 0 and 1");
  38. }
  39. String tmp = String.format("%." + decimalPlaces + "f", value);
  40. return tmp.substring(1);
  41. }
  42.  
  43.  
  44. }
Success #stdin #stdout 0.1s 380736KB
stdin
Standard input is empty
stdout
.5
.03
.349
.985
.66667
---------
.5
.03
.349
.985
.66667