今天写程序遇到了一个对double数进行四舍五入的需求,Google了一下全是J2SE版本的,没办法只好自己实现。
但J2ME的Math包功能少的可怜,看来用普通方法是不行了!想了想,只有把它转成字符串再进行操作了,具体实现如下:
public static double round(double operand, int saveBitNum){
double result;
int i = Double.toString(operand).indexOf(".");
char ch[] = Double.toString(operand).toCharArray();
if(i + 1 + saveBitNum >= ch.length){
return operand;
}
if(Character.digit(ch[i+saveBitNum+1], 10) < 5){
for(int j = i+saveBitNum+1; j < ch.length; j++){
ch[j] = 0;
}
result = Double.parseDouble(new String(ch));
}
else{
for(int j = i+saveBitNum+1; j < ch.length; j++){
ch[j] = 0;
}
int t;
if(saveBitNum == 0){
t = Character.digit(ch[i-1],10)+1;
ch[i-1] = String.valueOf(t).charAt(0);
result = Double.parseDouble(new String(ch));
}
else{
t = Character.digit(ch[i+saveBitNum],10)+1;
if(t == 10){
t = 0;
ch[i+saveBitNum] = String.valueOf(t).charAt(0);
result = round(operand,saveBitNum-1);
}
else{
ch[i+saveBitNum] = String.valueOf(t).charAt(0);
result = Double.parseDouble(new String(ch));
}
}
}
return result;
}
public static double round1(double operand, int saveBitNum){ //余位皆舍
int i = Double.toString(operand).indexOf(".");
char ch[] = Double.toString(operand).toCharArray();
if(i + 1 + saveBitNum >= ch.length){
return operand;
}
for(int j = i+saveBitNum+1; j < ch.length; j++){
ch[j] = 0;
}
return Double.parseDouble(new String(ch));
}
public static double round2(double operand, int saveBitNum){ //余位皆入
double result;
int i = Double.toString(operand).indexOf(".");
char ch[] = Double.toString(operand).toCharArray();
if(i + 1 + saveBitNum >= ch.length){
return operand;
}
for(int j = i+saveBitNum+1; j < ch.length; j++){
ch[j] = 0;
}
int t;
if(saveBitNum == 0){ //取整
t = Character.digit(ch[i-1],10)+1;
ch[i-1] = String.valueOf(t).charAt(0);
result = Double.parseDouble(new String(ch));
}
else{
t = Character.digit(ch[i+saveBitNum],10)+1;
if(t == 10){
t = 0;
ch[i+saveBitNum] = String.valueOf(t).charAt(0);
result = round(operand,saveBitNum-1);
}
else{
ch[i+saveBitNum] = String.valueOf(t).charAt(0);
result = Double.parseDouble(new String(ch));
}
}
return result;
}