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.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…