/*Java 两个整数相除保留两位小数*/
float num= (float)40.5/100;
DecimalFormat df = new DecimalFormat(“0.00”);//格式化小数
String s = df.format(num);//返回的是String类型
System.out.println(s);
/* 小数转换成百分数*/
double percent = (double)5/15;
double percent3 = (double)0/1;
NumberFormat nt = NumberFormat.getPercentInstance();//获取格式化对象
nt.setMinimumFractionDigits(2);//设置百分数精确度2即保留两位小数
System.out.println(“百分数1:” + nt.format(percent));//最后格式化并输出
System.out.println(“百分数3:” + nt.format(percent3));
/* Java获取时间差,分钟差*/
SimpleDateFormat dfs = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);
Date from=(Date) dfs.parse(“2017-10-07 14:14:00”);
Date to = (Date) dfs.parse(“2017-10-07 14:30:00”);
long minutes=(to.getTime()-from.getTime())/(1000*60);//除以1000是为了转换成秒 System.out.println(minutes);
控制台输出结果:
0.41
百分数1:33.33%
百分数3:0.00%
16
//如何根据hashMap中的value值进行排序。
package
Map;
import
java.util.ArrayList;
import
java.util.Collections;
import
java.util.Comparator;
import
java.util.List;
import
java.util.Map;
import
java.util.Map.Entry;
import
java.util.TreeMap;
public
class
SortMap {
public
static
void
main(String[] args) {
Map map=
new
TreeMap ();
map.put(
"图书"
,
4
);
map.put(
"音像"
,
6
);
map.put(
"素材"
,
9
);
map.put(
"音乐"
,
8
);
map.put(
"影视"
,
7
);
map.put(
"动漫"
,
4
);
map.put(
"歌曲"
,
3
);
map.put(
"图片"
,
2
);
map.put(
"图标"
,
6
);
ArrayList<Map.Entry<String,Integer>> entries= sortMap(map);
for
(
int
i=
0
;i<
5
;i++){
System. out.print(entries.get(i).getKey()+
":"
+entries.get(i).getValue());
}
}
public
static
ArrayList<Map.Entry<String,Integer>> sortMap(Map map){
List<Map.Entry<String, Integer>> entries =
new
ArrayList<Map.Entry<String, Integer>>(map.entrySet());
Collections.sort(entries,
new
Comparator<Map.Entry<String, Integer>>() {
public
int
compare(Map.Entry<String, Integer> obj1 , Map.Entry<String, Integer> obj2) {
return
obj2.getValue() - obj1.getValue();
}
});
return
(ArrayList<Entry<String, Integer>>) entries;
}
}