我想使用DecimalFormat格式化数字 最大整数(和小数)位数必须为2 如果数字是345561.7301,那么期望的结果将是:61.73
这是我的代码:
double number = 345561.7301;
DecimalFormat formater =
(DecimalFormat)DecimalFormat.getInstance(Locale.US);//This locale only
formater.applyPattern("00.00");
System.out.println(formater.format(number));
我不想使用setMaximumIntegerDigits()方法。
答案 0 :(得分:2)
如何使用子字符串?
double number = 345561.7301;
DecimalFormat formater =
(DecimalFormat)DecimalFormat.getInstance(Locale.US); //This locale only
formater.applyPattern("00.00");
//formater.setMaximumIntegerDigits(2); // <- don't want to use this
String tmp = formater.format(number);
System.out.println(tmp.substring(tmp.length() - 5));
答案 1 :(得分:0)
在此方案中,使用模式可能不是最佳选择。我建议使用模数除法'%'并得到数字/ 100的余数。
double number = 345561.7301 % 100;
DecimalFormat formater = (DecimalFormat)DecimalFormat.getInstance(Locale.US);
formater.applyPattern("00.00");
System.out.println(formater.format(number));