]> gitweb.fperrin.net Git - GpsPrune.git/blob - src/tim/prune/data/NumberUtils.java
652e8243af2fc85d01dfb2940bc007bc0c755927
[GpsPrune.git] / src / tim / prune / data / NumberUtils.java
1 package tim.prune.data;
2
3 import java.text.DecimalFormat;
4 import java.text.NumberFormat;
5 import java.util.Locale;
6
7 /**
8  * Abstract class to offer general number manipulation functions
9  */
10 public abstract class NumberUtils
11 {
12         /** UK-specific number formatter object to avoid lots of instantiations */
13         private static final NumberFormat UK_FORMAT = NumberFormat.getNumberInstance(Locale.UK);
14         // Select the UK locale for this formatter so that decimal point is always used (not comma)
15         static {
16                 if (UK_FORMAT instanceof DecimalFormat) ((DecimalFormat) UK_FORMAT).applyPattern("0.000");
17         }
18
19         /**
20          * Find the number of decimal places represented in the String
21          * @param inString String to check
22          * @return number of decimal places, or 0 for integer value
23          */
24         public static int getDecimalPlaces(String inString)
25         {
26                 if (inString == null || inString.equals("")) {return 0;}
27                 int places = 0;
28                 final int sLen = inString.length();
29                 for (int i=sLen-1; i>=0; i--) {
30                         char c = inString.charAt(i);
31                         if (c >= '0' && c <= '9') {
32                                 // Numeric character found
33                                 places++;
34                         }
35                         else {
36                                 // Non-numeric character found, return places
37                                 return places;
38                         }
39                 }
40                 // No non-numeric characters found, so must be integer
41                 return 0;
42         }
43
44         /**
45          * Format the given number in UK format (decimal point) to the given number of decimal places
46          * @param inNumber double number to format
47          * @param inDecimalPlaces number of decimal places
48          */
49         public static String formatNumberUk(double inNumber, int inDecimalPlaces)
50         {
51                 UK_FORMAT.setMaximumFractionDigits(inDecimalPlaces);
52                 UK_FORMAT.setMinimumFractionDigits(inDecimalPlaces);
53                 return UK_FORMAT.format(inNumber);
54         }
55 }