bb.util
Class NumberUtil

java.lang.Object
  extended by bb.util.NumberUtil

public final class NumberUtil
extends Object

Provides static utility methods related to numbers.

This class is multithread safe: most of its state is immutable (both its immediate state, as well as the deep state of its fields). The sole exception is the scientificNotationFormat field, however, all uses of that field first synchronize on it.

Author:
Brent Boyer
See Also:
IEEE Standard 754 Floating Point Numbers

Nested Class Summary
static class NumberUtil.UnitTest
          See the Overview page of the project's javadocs for a general description of this unit test class.
 
Field Summary
static int countHardCases
          Number of hard to parse cases that parseDouble has encountered so far.
private static char decimalSeparator
           
private static int exponentDoubleMax
           
private static int exponentDoubleMin
           
private static boolean isZeroDigit0
           
private static int magnitudeExactMax
           
private static double[] magnitudesExact
          All the positive powers of 10 that can be represented exactly as a double.
private static char minusSign
           
private static String nanText
           
private static int nDigitsIntMax
          If an int is written using decimal digits, this field records the maximum number of digits that could be present.
private static int nDigitsLongMax
          If a long is written using decimal digits, this field records the maximum number of digits that could be present.
private static int nDigitsMantissaMax
          If the mantissa of a double is written as a (positive) integer using decimal digits, this field records the maximum number of digits that could be present.
private static String negativeInfinityText
           
private static String positiveInfinityText
           
private static DecimalFormat scientificNotationFormat
           
static int unsigned2ByteMaxValue
          Maximum value of an unsigned 2 byte integer, namely, 2^16 - 1 = 65535.
private static char zeroDigit
           
 
Constructor Summary
private NumberUtil()
          This private constructor suppresses the default (public) constructor, ensuring non-instantiability.
 
Method Summary
static int bytesBigEndianToInt(byte[] bytes)
          Converts an array of 4 bytes in big endian order (i.e. bytes[0] is the most significant byte) to an int which is returned.
static long bytesBigEndianToLong(byte[] bytes)
          Converts an array of 8 bytes in big endian order (i.e. bytes[0] is the most significant byte) to a long which is returned.
static int bytesLittleEndianToInt(byte[] bytes)
          Converts an array of 4 bytes in little endian order (i.e. bytes[0] is the least significant byte) to an int which is returned.
static long bytesLittleEndianToLong(byte[] bytes)
          Converts an array of 8 bytes in little endian order (i.e. bytes[0] is the least significant byte) to a long which is returned.
private static int digitToInt(char c)
           
private static long digitToLong(char c)
           
static int getMillValue(double d)
          Rounds d to the nearest mill (i.e. third decimal place, 0.001) and returns the mill digit.
static boolean isEven(int i)
          Determines whether or not i is an even number.
static boolean isNormal(double d)
          Determines whether or not d is a "normal" double (i.e. that d is not NaN or infinite).
static boolean isNormal(float f)
          Determines whether or not f is a "normal" float, which is defined as f is not NaN or infinite.
static boolean isOdd(int i)
          Determines whether or not i is an odd number.
static double max(double d1, double d2)
          Returns the maximum value of d1 and d2.
static double min(double d1, double d2)
          Returns the minimum value of d1 and d2.
static double parseDouble(String s)
          Parses a double from s.
static int parseInt(char[] chars, int indexStart, int indexStop)
          Same as parseInt(s), except that this version operates on a char[] instead of a String.
static int parseInt(String s)
          Parses an int from s.
static int parseInt(String s, int indexStart, int indexStop)
          Parses an int from the specified substring of s.
static long parseLong(String s)
          Parses a long from s.
static double roundToCent(double d)
          Rounds d to the nearest cent (i.e. second decimal place, 0.01) and returns this.
static double roundToMill(double d)
          Rounds d to the nearest mill (i.e. third decimal place, 0.001) and returns this.
static String toScientificNotation(double d)
          Formats d as a String in scientific notation.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

nDigitsIntMax

private static final int nDigitsIntMax
If an int is written using decimal digits, this field records the maximum number of digits that could be present. Note: this values does not include any optional sign char.

See Also:
Constant Field Values

nDigitsLongMax

private static final int nDigitsLongMax
If a long is written using decimal digits, this field records the maximum number of digits that could be present. Note: this values does not include any optional sign char.

See Also:
Constant Field Values

unsigned2ByteMaxValue

public static final int unsigned2ByteMaxValue
Maximum value of an unsigned 2 byte integer, namely, 2^16 - 1 = 65535.

See Also:
Constant Field Values

nDigitsMantissaMax

private static final int nDigitsMantissaMax
If the mantissa of a double is written as a (positive) integer using decimal digits, this field records the maximum number of digits that could be present.

See Also:
Constant Field Values

exponentDoubleMax

private static final int exponentDoubleMax
See Also:
Constant Field Values

exponentDoubleMin

private static final int exponentDoubleMin
See Also:
Constant Field Values

magnitudeExactMax

private static final int magnitudeExactMax
See Also:
Constant Field Values

magnitudesExact

private static final double[] magnitudesExact
All the positive powers of 10 that can be represented exactly as a double.

See Also:
UnitTest.find_magnitudeExactMax

scientificNotationFormat

private static final DecimalFormat scientificNotationFormat

nanText

private static final String nanText

negativeInfinityText

private static final String negativeInfinityText

positiveInfinityText

private static final String positiveInfinityText

decimalSeparator

private static final char decimalSeparator

minusSign

private static final char minusSign

zeroDigit

private static final char zeroDigit

isZeroDigit0

private static final boolean isZeroDigit0

countHardCases

public static volatile int countHardCases
Number of hard to parse cases that parseDouble has encountered so far.

Constructor Detail

NumberUtil

private NumberUtil()
This private constructor suppresses the default (public) constructor, ensuring non-instantiability.

Method Detail

isEven

public static boolean isEven(int i)
Determines whether or not i is an even number.


isOdd

public static boolean isOdd(int i)
Determines whether or not i is an odd number.


isNormal

public static boolean isNormal(double d)
Determines whether or not d is a "normal" double (i.e. that d is not NaN or infinite).


isNormal

public static boolean isNormal(float f)
Determines whether or not f is a "normal" float, which is defined as f is not NaN or infinite.


bytesBigEndianToInt

public static int bytesBigEndianToInt(byte[] bytes)
                               throws IllegalArgumentException
Converts an array of 4 bytes in big endian order (i.e. bytes[0] is the most significant byte) to an int which is returned. Just like DataInputStream.readInt, the bytes are treated as unsigned bit groups.

Throws:
IllegalArgumentException - if bytes == null; bytes.length != 4

bytesLittleEndianToInt

public static int bytesLittleEndianToInt(byte[] bytes)
                                  throws IllegalArgumentException
Converts an array of 4 bytes in little endian order (i.e. bytes[0] is the least significant byte) to an int which is returned. Just like DataInputStream.readInt, the bytes are treated as unsigned bit groups.

Throws:
IllegalArgumentException - if bytes == null; bytes.length != 4

bytesBigEndianToLong

public static long bytesBigEndianToLong(byte[] bytes)
                                 throws IllegalArgumentException
Converts an array of 8 bytes in big endian order (i.e. bytes[0] is the most significant byte) to a long which is returned. Just like DataInputStream.readLong, the bytes are treated as unsigned bit groups.

Throws:
IllegalArgumentException - if bytes == null; bytes.length != 8

bytesLittleEndianToLong

public static long bytesLittleEndianToLong(byte[] bytes)
                                    throws IllegalArgumentException
Converts an array of 8 bytes in little endian order (i.e. bytes[0] is the least significant byte) to a long which is returned. Just like DataInputStream.readLong, the bytes are treated as unsigned bit groups.

Throws:
IllegalArgumentException - if bytes == null; bytes.length != 8

min

public static double min(double d1,
                         double d2)
Returns the minimum value of d1 and d2. This method differs from Math.min solely in how it handles NaN inputs: it only returns NaN if both args are NaN; if exactly one arg is NaN, the other arg is always returned regardless of its value; and if neither arg is NaN then the result of Math.min(d1, d2) is returned. In contrast, Math.min always returns NaN if either arg is NaN.


max

public static double max(double d1,
                         double d2)
Returns the maximum value of d1 and d2. This method differs from Math.max solely in how it handles NaN inputs: it only returns NaN if both args are NaN; if exactly one arg is NaN, the other arg is always returned regardless of its value; and if neither arg is NaN then the result of Math.max(d1, d2) is returned. In contrast, Math.max always returns NaN if either arg is NaN.


roundToCent

public static double roundToCent(double d)
                          throws IllegalArgumentException
Rounds d to the nearest cent (i.e. second decimal place, 0.01) and returns this.

Throws:
IllegalArgumentException - if d is not normal;

roundToMill

public static double roundToMill(double d)
                          throws IllegalArgumentException
Rounds d to the nearest mill (i.e. third decimal place, 0.001) and returns this.

Throws:
IllegalArgumentException - if d is not normal;

getMillValue

public static int getMillValue(double d)
                        throws IllegalArgumentException
Rounds d to the nearest mill (i.e. third decimal place, 0.001) and returns the mill digit.

Throws:
IllegalArgumentException - if d is not normal;

toScientificNotation

public static String toScientificNotation(double d)
Formats d as a String in scientific notation. The special values NaN, NEGATIVE_INFINITY, and POSITIVE_INFINITY are returned as String.valueOf(d).


parseDouble

public static double parseDouble(String s)
                          throws NumberFormatException
Parses a double from s.

This method can usually parse s in any format that is parsable by Double.parseDouble. (See Double.valueOf for details.) In particular, this means that:

  1. s should contain no grouping separator chars (e.g. commas)
  2. leading zeroes (in both the mantissa and exponent) will correctly be ignored
Exceptions regarding the format of s:
  1. this method uses the locale specific zero char, which may or may not be '0'; Double.parseDouble rigidly assumes '0' always
  2. like parseInt/parseLong (from either NumberUtil or Integer/Long), but unlike Double.parseDouble, this method does not trim leading and trailing whitespace and will throw a NumberFormatException if such whitespace is encountered.

Some of the code here was inspired by the non-public class java.lang.FloatingDecimal (must have access to Sun's java source code to view this).

Throws:
NumberFormatException - if s is in the wrong format

parseInt

public static int parseInt(String s)
                    throws NumberFormatException
Parses an int from s. This method simply returns parseInt(s, 0, s.length()).

Throws:
NumberFormatException - if s is in the wrong format

parseInt

public static int parseInt(String s,
                           int indexStart,
                           int indexStop)
                    throws NumberFormatException
Parses an int from the specified substring of s.

The substring must follow the same format as the String supplied to Integer.parseInt. In particular, this means that:

  1. the substring should contain no grouping separator chars (e.g. commas)
  2. the substring should have no leading or trailing whitespace
  3. leading zeroes may be present

Parameters:
s - the String which is the source of chars that will parse into an int
indexStart - the index (inclusive) of s that will begin parsing from
indexStop - the index (exclusive) of s that will stop parsing at
Throws:
NumberFormatException - if there is any problem with a parameter

parseInt

public static int parseInt(char[] chars,
                           int indexStart,
                           int indexStop)
                    throws NumberFormatException
Same as parseInt(s), except that this version operates on a char[] instead of a String. This method is generally faster for an equivalent stream of chars, since can immediately access all the chars without invoking an accessor method.

Parameters:
chars - the source of chars that will parse into an int
indexStart - the index (inclusive) of chars that will begin parsing from
indexStop - the index (exclusive) of chars that will stop parsing at
Throws:
NumberFormatException - if chars is in the wrong format or if there is any problem with the other parameters

parseLong

public static long parseLong(String s)
                      throws NumberFormatException
Parses a long from s.

This method can parse s in any format that is parsable by Long.parseLong. In particular, this means that:

  1. s should contain no grouping separator chars (e.g. commas)
  2. leading or trailing whitespace has previously been trimmed from s (e.g. for either NumberUtil or Long, calling parseLong(" 123 ") will result in a NumberFormatException)
  3. leading zeroes will correctly be ignored

Throws:
NumberFormatException - if s is in the wrong format

digitToInt

private static int digitToInt(char c)
                       throws NumberFormatException
Throws:
NumberFormatException

digitToLong

private static long digitToLong(char c)
                         throws NumberFormatException
Throws:
NumberFormatException