1 /* Open Log Viewer
2 *
3 * Copyright 2011
4 *
5 * This file is part of the OpenLogViewer project.
6 *
7 * OpenLogViewer software is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * OpenLogViewer software is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with any OpenLogViewer software. If not, see http://www.gnu.org/licenses/
19 *
20 * I ask that if you make any changes to this file you fork the code on github.com!
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 * MathUtils is used to provide math functions specific to the project.
31 * @author Ben Fenner
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 * @param input - The double you'd like to round the decimal places for
48 * @param decimalPlaces - The number of decimal places you'd like
49 * @return the formatted number
50 */
51 public static String roundDecimalPlaces(final double input, final int decimalPlaces) {
52 // Deal with zero or negative decimal places requested
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 // Deal with negative zero
69 if (output.toString().equals(negativeZero.toString())) {
70 output.deleteCharAt(0);
71 }
72
73 return output.toString();
74 }
75 }