假设我想打印数字100000000。乍一看,很难知道这个数字代表多少百万。它是1000万还是1亿?如何使Java中的大数更易读?类似于这样的东西会很棒:100 000 000
。您可以立即确定该数字为1亿。
假设我想打印数字100000000。乍一看,很难知道这个数字代表多少百万。它是1000万还是1亿?如何使Java中的大数更易读?类似于这样的东西会很棒:100 000 000
。您可以立即确定该数字为1亿。
您也可以尝试使用 DecimalFormat;
DecimalFormat formatter = new DecimalFormat("#,###");
System.out.println(formatter.format(100000));
结果:
1000>>1,000
10000>>10,000
100000>>100,000
1000000>>1,000,000
你可以尝试像这样做:
String.format("%.2fM", yourNumber/ 1000000.0);
1,000,000 => 1.00M
1,234,567 => 1.23M
编辑:
我知道这是一次迟到的编辑,但还有另外一种方法:
private static String[] suff = new String[]{"","k", "m", "b", "t"};
private static int MAX_LENGTH = 4;
private static String numberFormat(double d) {
String str = new DecimalFormat("##0E0").format(d);
str = str.replaceAll("E[0-9]", suff[Character.getNumericValue(str.charAt(str.length() - 1)) / 3]);
while(str.length() > MAX_LENGTH || str.matches("[0-9]+\\.[a-z]")){
str = str.substring(0, str.length()-2) + str.substring(str.length() - 1);
}
return str;
}
201700 = 202k
3000000 = 3m
8800000 = 8.8m
DecimalFormat myFormatter = new DecimalFormat("### ### ###");
String output = myFormatter.format(value);
System.out.println(output);
DecimalFormat decimalFormat = new DecimalFormat("###,###,###");
System.out.println(decimalFormat.format(100000000));
DecimalFormatSymbols customSymbols = DecimalFormatSymbols.getInstance(Locale.US);
customSymbols.setGroupingSeparator(' ');
new DecimalFormat("#,###;-#,###", customSymbols).format(value);
"#,###;-#,###" 中的分号用于分隔正数和负数(必须分别定义,否则所有数字都将转换为正数!)
冒号用于指定数字的位数分隔符(在此示例中每3个数字一个分隔符)。
例如:
value=12345678
12 345 678
你可能只需要使用字符串来处理这个问题。如果你需要进行一些计算,可以将其保留为整数,直到需要打印出来时再将其转换为字符串,处理字符串使其易读,并打印出来。