rt。
1.在java中我想对金额进行格式化2.两种情况2.1 少于100
String money="10";经过转换之后,输入为“0.10”(元).2.2 大于100
String money="900";经过转换之后,输入为“9.00”(元).
这是我之前写的,但是少于100就有问题了:
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;
}Java格式化String
1.在java中我想对金额进行格式化2.两种情况2.1 少于100
String money="10";经过转换之后,输入为“0.10”(元).2.2 大于100
String money="900";经过转换之后,输入为“9.00”(元).
这是我之前写的,但是少于100就有问题了:
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;
}Java格式化String
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();
}
}
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 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,你会死得很难看”,“精度问题”请问我这段代码还有什么地方需要优化的?
1 小于100出问题,你大于100都出问题,请找本基础书,看看什么叫“整除”
2 显示在屏幕上的,那个叫“输出”,否则干嘛叫System.out.....,你键盘打的,叫“输入”,否则干嘛叫“输入法”另外,"#,##0.00",注意小数点前面的那个0,如果你用#,那么0.1会变成.10而不是通常你期望的0.10。而前面那么多#,###,###是多余的,只要一个逗号,能够明确表明多少数字一节即可。最后,精确计算时,不要使用float或double