Java:格式数以百万计

时间:2009-02-09 19:06:24

标签: java formatting numeric numericupdown

有没有办法使用DecimalFormat(或其他一些标准格式化程序)来格式化这样的数字:

  

1,000,000 => 1.00M

     

1,234,567 => 1.23M

     

1,234,567,890 => 1234.57M

基本上将一些数字除以1百万,保留2位小数,并在末尾打一个“M”。我已经考虑过创建一个新的NumberFormat子类,但它看起来比我想象的要复杂。

我正在编写一个API,其格式方法如下所示:

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

在内部,我将Unit对象映射到NumberFormatters。实现是这样的:

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

请注意,由于这个原因,我不能指望客户端除以100万,我不能只使用String.format()而不将其包装在NumberFormatter中。

8 个答案:

答案 0 :(得分:18)

String.format("%.2fM", theNumber/ 1000000.0);

有关详细信息,请参阅String.format javadocs

答案 1 :(得分:4)

请注意,如果您有BigDecimal,则可以使用movePointLeft方法:

new DecimalFormat("#.00").format(value.movePointLeft(6));

答案 2 :(得分:3)

这是我掀起的NumberFormat的子类。它看起来像是完成了工作,但我不完全确定这是最好的方法:

private static final NumberFormat MILLIONS = new NumberFormat()
{
    private NumberFormat LOCAL_REAL = new DecimalFormat("#,##0.00M");

    public StringBuffer format(double number, StringBuffer toAppendTo, FieldPosition pos)
    {
        double millions = number / 1000000D;
        if(millions > 0.1) LOCAL_REAL.format(millions, toAppendTo, pos);

        return toAppendTo;
    }

    public StringBuffer format(long number, StringBuffer toAppendTo, FieldPosition pos)
    {
        return format((double) number, toAppendTo, pos);
    }

    public Number parse(String source, ParsePosition parsePosition)
    {
        throw new UnsupportedOperationException("Not implemented...");
    }
};

答案 3 :(得分:3)

为什么不简单?

DecimalFormat df = new DecimalFormat("0.00M");
System.out.println(df.format(n / 1000000));

答案 4 :(得分:0)

看看ChoiseFormat

更简单的方法是使用一个自动除以1米的包装器。

答案 5 :(得分:0)

现在,您应该使用ICU的CompactDecimalFormat,它将本地化​​非英语语言环境的格式化结果。其他语言环境可能不使用“ Millions”后缀。

This functionality will be standard Java in JDK 12CompactNumberFormat

答案 6 :(得分:0)

对于那些希望在那里以人类可读形式转换给定数字的人来说。

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);

}

答案 7 :(得分:0)

在Kotlin语言中,您可以启用扩展功能:

fun Long.formatToShortNumber(): String {
    return when {
        this >= 1000000000 -> String.format("%.2fB", this / 1000000000.0)
        this >= 1000000 -> String.format("%.2fM", this / 1000000.0)
        this >= 1000 -> String.format("%.2fK", this / 1000.0)
        else -> this.toString()
    }
}
相关问题