Format.java 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package holeg.utility.math.decimal;
  2. import java.math.RoundingMode;
  3. import java.text.DecimalFormat;
  4. import java.text.NumberFormat;
  5. import java.util.Locale;
  6. /**
  7. * A class with format shortcuts for common formats.
  8. */
  9. public class Format {
  10. private static final DecimalFormat formatter;
  11. private static final DecimalFormat twoFormatter;
  12. static {
  13. // Initializes the formatters statically
  14. NumberFormat nf = NumberFormat.getNumberInstance(Locale.US);
  15. formatter = (DecimalFormat) nf;
  16. formatter.applyPattern("#.###########");
  17. formatter.setRoundingMode(RoundingMode.UP);
  18. twoFormatter = (DecimalFormat) nf;
  19. twoFormatter.applyPattern("#.##");
  20. twoFormatter.setRoundingMode(RoundingMode.UP);
  21. }
  22. /**
  23. * Format a double with variable amount of places.
  24. * @param places the amount of decimals after the '.' - separator
  25. * @param value the value to format
  26. * @return the formatted string
  27. */
  28. public static String doubleFixedPlaces(int places, double value) {
  29. return String.format(Locale.US, "%." + places + "f", value);
  30. }
  31. /**
  32. * Format a double value with two decimals after the '.' - separator.
  33. * @param value the value to format
  34. * @return the formatted string
  35. */
  36. public static String doubleTwoPlaces(double value) {
  37. return twoFormatter.format(value);
  38. }
  39. /**
  40. * Format a double value with ten decimals after the '.' - separator.
  41. * @param value the value to format
  42. * @return the formatted string
  43. */
  44. public static String doubleAllPlaces(double value) {
  45. return formatter.format(value);
  46. }
  47. }