问题
I have a requirement to show a number value like 123456789.905
in the following format 123,456,789.90
. But the comma separation changes depending on the locale selected in the phone (as if with US English selected comma separation is 3 places and if India English is selected it is like 12,34,56,789.90
).
How can I format my Double
?
回答1:
So, java.text.NumberFormat
doesn't slove the problem, unfortunately, but com.ibm.icu.text.NumberFormat does.
You can use this:
Double d = 123456789.905;
com.ibm.icu.text.NumberFormat format = com.ibm.icu.text.NumberFormat.getNumberInstance(new Locale("en", "in"));
format.setMinimumFractionDigits(2);
format.setMaximumFractionDigits(2);
System.out.println(format.format(d));
This outputs: 12,34,56,789.90
.
回答2:
For the generic case, use java.text.NumberFormat:
NumberFormat nf = NumberFormat.getInstance();
String formatted = nf.format(yourDoubleValue);
By default getInstance()
returns a NumberFormat
that is configured as appropriate for the current Locale
. You can change the configuration yourself, too.
The "comma separation" is called "grouping".
For the specific case of grouping in an Indian currency format, see: Displaying Currency in Indian Numbering Format
回答3:
Try this one:
try {
Locale l = Locale.getDefault();
NumberFormat nf = NumberFormat.getInstance(l);
String formato = NumberFormat.getInstance().format(your_data);
} catch (Exception e) {
e.printStackTrace();}
回答4:
Use NumberFormat, which helps you to format and parse numbers for any locale.
Your code can be completely independent of the locale conventions for decimal points, thousands-separators, or even the particular decimal digits used, or whether the number format is even decimal.
Locale fmtLocale = Locale.getDefault();
NumberFormat formatter = NumberFormat.getInstance(fmtLocale);
formatter.format(your_number);
回答5:
Hm, I have not found for any locale in NumberFormat.getAvailableLocales()
a format with only two digits between grouping signs (for example for new Locale("en", "IN")
). So I think you have to use DecimalFormat-pattern like this:
DecimalFormat df = new DecimalFormat("##,##,##,##,##.###");
System.out.println(df.format(123456789.905));
// Output: 1.23.45.67.89,905
It is not exactly the same since DecimalFormat is not able to have varying counts of grouping sizes, but maybe this is acceptable for you.
回答6:
NumberFormat nf = NumberFormat.getInstance(Locale.getDefault());
double value = nf.parse(iValue).doubleValue();
来源:https://stackoverflow.com/questions/20883402/number-format-comma-separation-as-per-locale