Class SizeExpression


  • public final class SizeExpression
    extends Object
    Tool for parsing and formatting SI-prefixed numbers in base-2 and base-10.
    • Constructor Detail

      • SizeExpression

        private SizeExpression()
        Prevent Instantiation.
    • Method Detail

      • parse

        public static long parse​(String expression)
        Parses the given expression into a numerical value.

        An expression has three parts:

        Size Summary Table
        Name Description
        Base Number (Required) The mantissa or significand of the expression. This can include decimal values.
        Prefix (Optional) The SI prefix. These span from K for kilo- to P for peta-.
        Unit (Optional) If the unit "B" (for bytes) is provided, the prefix is treated as base-2 (1024). Otherwise, it uses base-10 (1000).
        Note: Whitespace may or may not exist between the Base Number and Prefix.

        Examples:

        • "2k" returns 2000
        • "3.5m" returns 3500000
        • "2kb" returns 2048
        • "3.5mb" returns 3670016
        Parameters:
        expression - the expression to parse
        Returns:
        the parsed value
        Throws:
        NumberFormatException - if the given expression cannot be parsed
      • format

        public static String format​(long value,
                                    int decimalPlaces,
                                    boolean base2)
        Formats the value as an expression.
        Parameters:
        value - the numerical value to be formatted
        decimalPlaces - the number of decimal places in the mantissa
        base2 - whether to use the base-2 (1024) multiplier and format with "B" units. If false, uses the base-10 (1000) multiplier and no units.
        Returns:
        a formatted string expression of the value
      • round

        private static double round​(double value,
                                    int decimalPlaces)
        Rounds a decimal value to the given decimal place.
        Parameters:
        value - the value to round
        decimalPlaces - the number of decimal places to preserve.
        Returns:
        the rounded value
      • multiplier

        private static double multiplier​(char unitPrefix,
                                         boolean base2)
        Returns the base-2 or base-10 multiplier for a given prefix.
        Parameters:
        unitPrefix - the character representing the prefix. Can be K, M, G, T, or P.
        base2 - whether to use the base-2 (1024) multiplier. If false, uses the base-10 (1000) multiplier.
        Returns:
        the multiplier for the given prefix