Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
797 views
in Technique[技术] by (71.8m points)

formatting - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
String.format("%.2fM", theNumber/ 1000000.0);

For more information see the String.format javadocs.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...