NumberFormat problem
http://www.exampledepot.com/egs/java.text/FormatNum.html
i开发者_StackOverflow have number 1.23 and i want to format it to 1,23. But if i have just 1 then i do not want format it to 1,00.
With ##,##0.00 i format 1.23 to 1,23 and 1 to 1,00. How can i format 1.23 to 1,23 and 1 to 1.
NumberFormat format = NumberFormat.getNumberInstance();
format.setMaximumFractionDigits(2);
format.setMinimumFractionDigits(0);
System.out.println(format.format(1.23));
System.out.println(format.format(1.0));
Try this pattern instead: ##,###.##
DecimalFormat df = new DecimalFormat("##,###.##");
System.out.println(df.format(1.00));
System.out.println(df.format(1.23));
prints:
1
1.23
The 0
in the pattern shows zeros as "0", while #
shows zeros as absent.
Perhaps this helps.
public class Main {
public static void main(String[] args) {
double f1 = 1;
System.out.printf("f1: %.2f%n", f1); // prints f1: 1.00
double f2 = 1.23;
System.out.printf("f2: %.2f%n", f2); // prints f2: 1.23
}
}
try this:
rewritten asela's and grodriguez's answers
DecimalFormatSymbols symbols = new DecimalFormatSymbols(); symbols.setDecimalSeparator(','); DecimalFormat format = new DecimalFormat("###.##", symbols); System.out.println(format.format(1.00)); System.out.println(format.format(1.23));
output:
1
1,23
Cheers!
-Saligh
If your Locale, country settings, have decimal comma as decimal separator, then it's already handled by java, like for the swedish locale:
double number = 1.23;
double otherNumber = 1.00;
System.out.println(NumberFormat.getInstance(new Locale("sv")).format(number));
System.out.println(NumberFormat.getInstance(Locale.ENGLISH).format(number));
System.out.println(NumberFormat.getInstance(new Locale("sv")).format(otherNumber));
System.out.println(NumberFormat.getInstance(Locale.ENGLISH).format(otherNumber));
which prints
1,23
1.23
1
1
Seems to be you can address the issue with local, Use Frech as your local for Decimal Format. Then you'll get ',' instead of '.'
NumberFormat f = NumberFormat.getInstance(local);
if (f instanceof DecimalFormat) {
((DecimalFormat) f).setDecimalSeparatorAlwaysShown(true);
}
or as below you can do it
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setDecimalSeparator(',');
DecimalFormat format = new DecimalFormat("###.00",symbols);
System.out.println(format.format(1.22));
精彩评论