1 import java.text.NumberFormat;
2
3 /**
4 * Created by Charlie on 2016/12/6.
5 * 通用字符串管理类
6 */
7 public class StringUtils {
8
9 /**
10 * 将double转为数值,并最多保留num位小数。例如当num为2时,1.268为1.27,1.2仍为1.2;1仍为1,而非1.00;100.00则返回100。
11 *
12 * @param d
13 * @param num 小数位数
14 * @return
15 */
16 public static String double2String(double d, int num) {
17 NumberFormat nf = NumberFormat.getNumberInstance();
18 nf.setMaximumFractionDigits(num);//保留两位小数
19 nf.setGroupingUsed(false);//去掉数值中的千位分隔符
20
21 String temp = nf.format(d);
22 if (temp.contains(".")) {
23 String s1 = temp.split("\\.")[0];
24 String s2 = temp.split("\\.")[1];
25 for (int i = s2.length(); i > 0; --i) {
26 if (!s2.substring(i - 1, i).equals("0")) {
27 return s1 + "." + s2.substring(0, i);
28 }
29 }
30 return s1;
31 }
32 return temp;
33 }
34
35 /**
36 * 将double转为数值,并最多保留num位小数。
37 *
38 * @param d
39 * @param num 小数个数
40 * @param defValue 默认值。当d为null时,返回该值。
41 * @return
42 */
43 public static String double2String(Double d, int num, String defValue){
44 if(d==null){
45 return defValue;
46 }
47
48 return double2String(d,num);
49 }
50 }