Number formatting in java to use Lakh format instead of million format

后端 未结 3 1350
伪装坚强ぢ
伪装坚强ぢ 2020-12-06 18:11

I have tried using NumberFormat and DecimalFormat. Even though I am using the en-In locale, the numbers are being formatted in Western

相关标签:
3条回答
  • 2020-12-06 18:45

    This kind of formatting is not possible to do with DecimalFormat. It only allows a fixed number of digits between the grouping separator.

    From the documentation:

    The grouping size is a constant number of digits between the grouping characters, such as 3 for 100,000,000 or 4 for 1,0000,0000. If you supply a pattern with multiple grouping characters, the interval between the last one and the end of the integer is the one that is used. So "#,##,###,####" == "######,####" == "##,####,####".

    If you want to get Lakhs format, you have to write some custom code.

    0 讨论(0)
  • 2020-12-06 18:50

    Since it is impossible with standard the Java formatters, I can offer a custom formatter

    public static void main(String[] args) throws Exception {
        System.out.println(formatLakh(123456.00));
    }
    
    private static String formatLakh(double d) {
        String s = String.format(Locale.UK, "%1.2f", Math.abs(d));
        s = s.replaceAll("(.+)(...\\...)", "$1,$2");
        while (s.matches("\\d{3,},.+")) {
            s = s.replaceAll("(\\d+)(\\d{2},.+)", "$1,$2");
        }
        return d < 0 ? ("-" + s) : s;
    }
    

    output

    1,23,456.00
    
    0 讨论(0)
  • 2020-12-06 19:00

    While the standard Java number formatter can't handle this format, the DecimalFormat class in ICU4J can.

    import com.ibm.icu.text.DecimalFormat;
    
    DecimalFormat f = new DecimalFormat("#,##,##0.00");
    System.out.println(f.format(1234567));
    // prints 12,34,567.00
    
    0 讨论(0)
提交回复
热议问题