Java: Format number in millions

前端 未结 8 2201
日久生厌
日久生厌 2020-12-10 14:01

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 =>

相关标签:
8条回答
  • 2020-12-10 14:27

    Note that if you have a BigDecimal, you can use the movePointLeft method:

    new DecimalFormat("#.00").format(value.movePointLeft(6));
    
    0 讨论(0)
  • 2020-12-10 14:27

    Here's a subclass of NumberFormat that I whipped up. It looks like it does the job but I'm not entirely sure it's the best way:

    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...");
        }
    };
    
    0 讨论(0)
  • 2020-12-10 14:31
    String.format("%.2fM", theNumber/ 1000000.0);
    

    For more information see the String.format javadocs.

    0 讨论(0)
  • 2020-12-10 14:36

    Why not simply?

    DecimalFormat df = new DecimalFormat("0.00M");
    System.out.println(df.format(n / 1000000));
    
    0 讨论(0)
  • 2020-12-10 14:39

    In Kotlin language, you can make extention function:

    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()
        }
    }
    
    0 讨论(0)
  • 2020-12-10 14:43

    Take a look at ChoiseFormat.

    A more simplistic way would be to use a wrapper that auto divided by 1m for you.

    0 讨论(0)
提交回复
热议问题