62,614
社区成员
发帖
与我相关
我的任务
分享
public String getDecimalFormat(String str){
Integer initValue=0;
String outStr = "";
if(str!=null&&!"".equals(str.trim())){
initValue=Integer.parseInt(str);
Integer yuanValue=initValue/100;
DecimalFormat fmt = new DecimalFormat("##,###,###,###,###.00");
double d;
try {
d = Double.parseDouble(String.valueOf(yuanValue));
outStr = fmt.format(d);
} catch (Exception e) {
e.printStackTrace();
}
}
return outStr;
}
public static String getFormatMoney(String str){
String moneyString = "";
float floatValue=0;
if(str!=null&&!"".equals(str.trim())){
floatValue=Float.parseFloat(str)/100;
moneyString=new DecimalFormat("0.00").format(floatValue);
}
return moneyString;
}
后来我用了这个方法,但是有个朋友说:“用parseFloat,你会死得很难看”,“精度问题”
请问我这段代码还有什么地方需要优化的?
public static String getDecimalFormat(String str){
double initValue=0;
String outStr = "";
if(str!=null&&!"".equals(str.trim())){
initValue=Double.parseDouble(str);
double yuanValue=initValue/100; //用double不会丢掉小数点后面的
DecimalFormat fmt = new DecimalFormat("##,###,###,###,##0.00");
double d;
try {
d = Double.parseDouble(String.valueOf(yuanValue));
outStr = fmt.format(d);
} catch (Exception e) {
e.printStackTrace();
}
}
return outStr;
}
String str="10";
Double initValue=0D;
String outStr = "";
if(str!=null&&!"".equals(str.trim())){
initValue= Double.parseDouble(str);
Double yuanValue=initValue/100;
System.out.println(yuanValue);
DecimalFormat fmt = new DecimalFormat("##,###,###,###,###0.00");
double d;
try {
d = Double.parseDouble(String.valueOf(yuanValue));
outStr = fmt.format(d);
System.out.println(outStr);
} catch (Exception e) {
e.printStackTrace();
}
}