Java: Format number in millions

前端 未结 8 2202
日久生厌
日久生厌 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:52

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

    For now, you should use ICU's CompactDecimalFormat, which will localize the formatting result for non-english locales. Other locales might not use a "Millions" suffix.

    This functionality will be standard Java in JDK 12 with CompactNumberFormat.

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