Java Number Readable Format toHumanReadableNum(final Number number)

Here you can find the source of toHumanReadableNum(final Number number)

Description

Tries to convert any number into an easily readable String representation.

License

Open Source License

Declaration

public static String toHumanReadableNum(final Number number) 

Method Source Code

//package com.java2s;
/*//from  ww  w . ja  va2s.  c o  m
 * Copyright (C) 2013 Universitat Pompeu Fabra
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

public class Main {
    /**
     * Tries to convert any number into an easily readable String representation.
     * for example: 123456789000 -> "123'456'789'000"
     */
    public static String toHumanReadableNum(final Number number) {

        String rep = number.toString();

        // split into parts
        final String signPart = rep.startsWith("-") ? "-" : "";
        final String integerPart = rep.substring(signPart.length()).replaceFirst("[^0-9].*$", "");
        final String restPart = rep.substring(signPart.length() + integerPart.length());

        // beautify the integer part
        final int n = integerPart.length();
        String integerPartNice = integerPart.substring(0, n % 3);
        for (int i = n % 3; i < n; i += 3) {
            if (!integerPartNice.isEmpty()) {
                integerPartNice += '\'';
            }
            integerPartNice += integerPart.substring(i, Math.min(i + 3, integerPart.length()));
        }

        rep = signPart + integerPartNice + restPart;

        return rep;
    }
}