對字符串的小數點後多餘的0用正則表達式進行切割處理

package test;  
  
/** 
 * 去掉多餘的.與0 
 * @author Hust 
 * @Time 2011-11-7 
 */  
public class TestString {  
  
    public static void main(String[] args) {  
        Float f = 1f;  
        System.out.println(f.toString());//1.0  
        System.out.println(subZeroAndDot("1"));;  // 轉換後爲1  
        System.out.println(subZeroAndDot("10"));;  // 轉換後爲10  
        System.out.println(subZeroAndDot("1.0"));;  // 轉換後爲1  
        System.out.println(subZeroAndDot("1.010"));;  // 轉換後爲1.01   
        System.out.println(subZeroAndDot("1.01"));;  // 轉換後爲1.01  
    }  
      
    /** 
     * 使用java正則表達式去掉多餘的.與0 
     * @param s 
     * @return  
     */  
    public static String subZeroAndDot(String s){  
        if(s.indexOf(".") > 0){  
            s = s.replaceAll("0+?$", "");//去掉多餘的0  
            s = s.replaceAll("[.]$", "");//如最後一位是.則去掉  
        }  
        return s;  
    }  
      
}  

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章