Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Format number in millions

Is there a way to use DecimalFormat (or some other standard formatter) to format numbers like this:

1,000,000 => 1.00M

1,234,567 => 1.23M

1,234,567,890 => 1234.57M

Basically dividing some number by 1 million, keeping 2 decimal places, and slapping an 'M' on the end. I've thought about creating a new subclass of NumberFormat but it looks trickier than I imagined.

I'm writing an API that has a format method that looks like this:

public String format(double value, Unit unit); // Unit is an enum

Internally, I'm mapping Unit objects to NumberFormatters. The implementation is something like this:

public String format(double value, Unit unit)
{
    NumberFormatter formatter = formatters.get(unit);
    return formatter.format(value);
}

Note that because of this, I can't expect the client to divide by 1 million, and I can't just use String.format() without wrapping it in a NumberFormatter.

like image 758
Outlaw Programmer Avatar asked Feb 09 '09 19:02

Outlaw Programmer


1 Answers

For someone looking out there to convert a given digit in human readable form.

public static String getHumanReadablePriceFromNumber(long number){

    if(number >= 1000000000){
        return String.format("%.2fB", number/ 1000000000.0);
    }

    if(number >= 1000000){
        return String.format("%.2fM", number/ 1000000.0);
    }

    if(number >= 100000){
        return String.format("%.2fL", number/ 100000.0);
    }

    if(number >=1000){
        return String.format("%.2fK", number/ 1000.0);
    }
    return String.valueOf(number);

}
like image 109
Muhammad Bilal ahmad Avatar answered Sep 28 '22 18:09

Muhammad Bilal ahmad