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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With