Formatting numbers in Java / Indian numbering syst

2019-08-04 15:46发布

问题:

This question already has an answer here:

  • How can I format a String number to have commas and round? 10 answers
  • Number formatting in java to use Lakh format instead of million format 3 answers

I want to obtain number in following format:

1000   =    1,000
10000  =   10,000
100000 = 1,00,000

I tried this:

import java.text.DecimalFormat;

public class StringProcessingDemo {

public static void main(String[] args) {
     String pattern = "##,##,###.###";
        DecimalFormat myFormatter = new DecimalFormat(pattern);
        String output = myFormatter.format(2564484.125);            
        System.out.println(output);
    }
}

But despite of pattern ##,##,###.### I am getting output as 2,564,484.125 while I think I should get it as 25,64,484.125. Why?

回答1:

You can achieve your requirement with this

public static String format(double value) {
    if(value < 1000) {
        return format("###", value);
    } else {
        double hundreds = value % 1000;
        int other = (int) (value / 1000);
        return format(",##", other) + ',' + format("000", hundreds);
    }
}

private static String format(String pattern, Object value) {
    return new DecimalFormat(pattern).format(value);
}


回答2:

But despite of pattern ##,##,###.### I am getting output as 2,564,484.125 while I think I should get it as 25,64,484.125. Why?

You can supply multiple grouping characters, but only one is used. From the Javadoc:

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 "#,##,###,####" == "######,####" == "##,####,####"

It seems that formatting the Lakh format is not possible with standard Java mechanisms, see Number formatting in java to use Lakh format instead of million format for a solution.



回答3:

This may be because of number format: million, billion, and trillion...... So, I have created a java function for your need:

String lakhFormattedComma(Double d) {
  String[] str = d.toString().split("\\.");
  int len = str[1].length();
  if (str[1].substring(len - 3, len - 1).equals("E-")) {
    return String.format("%." + (len - 3 + Integer.valueOf(str[1].substring(len - 1))) + "f", d);
  } else if (str[1].substring(len - 2, len - 1).equals("E")) {
    str = String.format("%." + (len - 2 - Integer.valueOf(str[1].substring(len - 1))) + "f", d).split("\\.");
  }
  String out = "." + str[1];
  len = str[0].length();
  if (len < 3) {
    return str[0] + out;
  }
  out = str[0].substring(len - 3) + out;
  for (int i = len - 5; i >= 0; i = i - 2) {
    out = str[0].substring(i, i + 2) + "," + out;
    if (i == 1) {
      out = str[0].substring(0, 1) + "," + out;
    }
  }
  return out;
}