1. 程式人生 > >Java獲取小數位數

Java獲取小數位數

/**
 * @(#)GetBitsOfDecimal.java
 *
 *
 * @author zhangweiheb
 * @version 1.00 2009/3/15
 */

import java.io.*;
import java.util.*;
import java.util.regex.*;

public class GetBitsOfDecimal {
 public static void main (String[] args) {
   
  //獲取鍵盤輸入
  String inStr="";
  System.out.println("輸入小數:");
  BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
  try{
  inStr=br.readLine();
  }catch(Exception e){}
 
  //正則表示式判斷是否為小數
  Pattern p=Pattern.compile("//d{1,}//.//d{1,}");
  Matcher m=p.matcher(inStr);
  boolean b=m.matches();
 
  if(b){                           //是小數則判斷位數
  //獲取小數點的位置
  int bitPos=inStr.indexOf(".");
 
  //字串總長度減去小數點位置,再減去1,就是小數位數
  int numOfBits=inStr.length()-bitPos-1;
  System.out.println("小數位數為: "+numOfBits);
  }else{                        //不是小數,給出錯誤提示資訊
  System.out.println("輸入的不是小數");
  } 
}  
}