J2ME版的“四舍五入”方法

今天写程序遇到了一个对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;
 }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值