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

后端 未结 3 1366
伪装坚强ぢ
伪装坚强ぢ 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条回答
  •  猫巷女王i
    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
    

提交回复
热议问题