File: NumberUtils.java

package info (click to toggle)
gpsprune 10-1
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 2,220 kB
  • ctags: 3,013
  • sloc: java: 22,662; sh: 23; makefile: 16; python: 15
file content (55 lines) | stat: -rw-r--r-- 1,650 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package tim.prune.data;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Locale;

/**
 * Abstract class to offer general number manipulation functions
 */
public abstract class NumberUtils
{
	/** Number formatter object to avoid lots of instantiations */
	private static final NumberFormat NUM_FORMATTER = NumberFormat.getNumberInstance(Locale.UK);
	// Select the UK locale for this formatter so that decimal point is always used (not comma)
	static {
		if (NUM_FORMATTER instanceof DecimalFormat) ((DecimalFormat) NUM_FORMATTER).applyPattern("0.000");
	}

	/**
	 * Find the number of decimal places represented in the String
	 * @param inString String to check
	 * @return number of decimal places, or 0 for integer value
	 */
	public static int getDecimalPlaces(String inString)
	{
		if (inString == null || inString.equals("")) {return 0;}
		int places = 0;
		final int sLen = inString.length();
		for (int i=sLen-1; i>=0; i--) {
			char c = inString.charAt(i);
			if (c >= '0' && c <= '9') {
				// Numeric character found
				places++;
			}
			else {
				// Non-numeric character found, return places
				return places;
			}
		}
		// No non-numeric characters found, so must be integer
		return 0;
	}

	/**
	 * Format the given number to the given number of decimal places
	 * @param inNumber double number to format
	 * @param inDecimalPlaces number of decimal places
	 */
	public static String formatNumber(double inNumber, int inDecimalPlaces)
	{
		NUM_FORMATTER.setMaximumFractionDigits(inDecimalPlaces);
		NUM_FORMATTER.setMinimumFractionDigits(inDecimalPlaces);
		return NUM_FORMATTER.format(inNumber);
	}
}