Shorthand

By Aion- on Sep 12, 2012

The following snippet returns the shorthand of the given value.

Examples:
shorthand(1234567, 0, false);
12M

shorthand(1234567, 2, false);
12.35M

shorthand(1234567, 2, true);
12.34M

shorthand(1234567, 3, false);
12.346M

shorthand(1234567, 3, true);
12.345M

    /**
     * Returns the shorthand of <code>number</code> rounded to <code>precision</code> significant figures.
     * <pre>    Metric prefixes
     * Symbol   Factor
     * &nbsp;&nbsp;k        &nbsp;10^3
     * &nbsp;&nbsp;M        &nbsp;10^6
     * &nbsp;&nbsp;G        &nbsp;10^9
     * &nbsp;&nbsp;T        &nbsp;10^12
     * &nbsp;&nbsp;P        &nbsp;10^15
     * &nbsp;&nbsp;E        &nbsp;10^18
     * &nbsp;&nbsp;Z        &nbsp;10^21
     * &nbsp;&nbsp;Y        &nbsp;10^24</pre>
     * <p><i>Note: A precision of 2 is used by default if necessary</i></p>
     *
     * @param number the number to get the shorthand of
     * @param precision the significant figures
     * @param keepAccuracy <tt>true</tt> to keep accuracy; otherwise <tt>false</tt>
     * @return the shorthand of <code>number</code> rounded to <code>precision</code> significant figures
     */
    public String shorthand(long number, int precision, boolean keepAccuracy) {
        String sign = number < 0 ? "-" : "";
        number = Math.abs(number);
        if (number < 1000) {
            return sign + number;
        } else if (precision < 0) {
            precision = 2;
        }
        int exponent = (int) (Math.log(number) / Math.log(1000));
        char suffix = "kMGTPEZY".charAt(exponent - 1);
        double significand = number / Math.pow(1000, exponent);
        if (!keepAccuracy) {
            return sign + String.format("%." + precision + "f%s", significand, suffix);
        } else {
            String result = String.valueOf(significand);
            if (precision == 0) {
                return sign + result.substring(0, result.indexOf(".")) + suffix;
            }
            int length = result.substring(result.indexOf(".") + 1).length();
            if (precision > length) {
                precision = 2;
            }
            return sign + result.substring(0, result.length() - (length - precision)) + suffix;
        }
    }

Comments

Sign in to comment.
Aion-   -  Oct 25, 2012

Updated. It now uses the official metric prefixes specified by SI.

http://en.wikipedia.org/wiki/Metric_prefix#List_of_prefixes

 Respond  
Sorasyn   -  Sep 12, 2012

If you even have a use for conversions beyond 2^31 you could implement the data type "long" it supports +/- 9,223,372,036,854,775,807.

Good to see some Java coming in!

 Respond  
Are you sure you want to unfollow this person?
Are you sure you want to delete this?
Click "Unsubscribe" to stop receiving notices pertaining to this post.
Click "Subscribe" to resume notices pertaining to this post.