Formatting numbers in Java / Indian numbering system [duplicate]

可紊 提交于 2019-12-11 07:56:50

问题


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;
}


来源:https://stackoverflow.com/questions/25078259/formatting-numbers-in-java-indian-numbering-system

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!