Java 数字格式问题
我有数字1.23,我想把它格式化成1,23。但是如果我只有1,那么我不想将其格式化为1,00Java 数字格式问题,java,Java,我有数字1.23,我想把它格式化成1,23。但是如果我只有1,那么我不想将其格式化为1,00 使用###,##0.00 i格式1.23到1,23和1到1,00。如何将1.23设置为1、23和1设置为1。似乎您可以使用local解决此问题,使用Frech作为十进制格式的local。然后你会得到“,”而不是“.” NumberFormat f = NumberFormat.getInstance(local); if (f instanceof DecimalFormat) { ((Deci
使用###,##0.00 i格式1.23到1,23和1到1,00。如何将1.23设置为1、23和1设置为1。似乎您可以使用local解决此问题,使用Frech作为十进制格式的local。然后你会得到“,”而不是“.”
NumberFormat f = NumberFormat.getInstance(local);
if (f instanceof DecimalFormat) {
((DecimalFormat) f).setDecimalSeparatorAlwaysShown(true);
}
或者像下面那样你可以做到
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setDecimalSeparator(',');
DecimalFormat format = new DecimalFormat("###.00",symbols);
System.out.println(format.format(1.22));
也许这有帮助
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
}
}
请尝试以下模式:
##########
印刷品:
1
1.23
模式中的0
将零显示为“0”,而#
将零显示为不存在。尝试以下操作:
改写了阿塞拉和格罗德里格斯的答案
DecimalFormatSymbols符号=新的DecimalFormatSymbols();
符号。setDecimalSeparator(',');
DecimalFormat=新的DecimalFormat(“####.##”,符号);
System.out.println(format.format(1.00));
System.out.println(format.format(1.23))
输出:
一,
1,23
干杯
-Saligh如果您的语言环境、国家/地区设置使用十进制逗号作为十进制分隔符,那么它已经由java处理,就像瑞典语言环境:
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));
哪张照片
1,231.23
1
1
1
1.23
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));