1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23 package org.diyefi.openlogviewer.utils;
24
25 import java.text.DecimalFormat;
26 import java.text.DecimalFormatSymbols;
27 import java.text.NumberFormat;
28
29
30
31
32
33 public final class MathUtils {
34 private static final char DS = DecimalFormatSymbols.getInstance().getDecimalSeparator();
35 private static final DecimalFormat CUSTOM = (DecimalFormat) NumberFormat.getNumberInstance();
36 private static final DecimalFormat NORMAL = (DecimalFormat) NumberFormat.getNumberInstance();
37 static {
38 CUSTOM.setGroupingUsed(false);
39 NORMAL.setGroupingUsed(false);
40 }
41
42 private MathUtils() {
43 }
44
45
46
47
48
49
50
51 public static String roundDecimalPlaces(final double input, final int decimalPlaces) {
52
53 if (decimalPlaces <= 0) {
54 return NORMAL.format(Math.round(input));
55 }
56
57 final StringBuilder format = new StringBuilder("###0" + DS);
58 final StringBuilder negativeZero = new StringBuilder("-0" + DS);
59
60 for (int i = 0; i < decimalPlaces; i++) {
61 format.append('0');
62 negativeZero.append('0');
63 }
64
65 CUSTOM.applyLocalizedPattern(format.toString());
66 final StringBuilder output = new StringBuilder(CUSTOM.format(input));
67
68
69 if (output.toString().equals(negativeZero.toString())) {
70 output.deleteCharAt(0);
71 }
72
73 return output.toString();
74 }
75 }