android EdItText保留兩位小數

private TextWatcher etNumTextWatcher = new TextWatcher() {

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
	}
	
	@Override
	public void beforeTextChanged(CharSequence s, int start, int count,
			int after) {
	}
	
	@Override
	public void afterTextChanged(Editable s) {
		
		if(mIsGram){
		//保留一位小數
			String temp = s.toString().trim();
			 int posDot = temp.indexOf(".");
		     if (posDot <= 0){
		    	 
		    	 if(s.length() > 1){
		    		 
		    		 if( s.charAt(0) == '0'){
		    			 
		    			 s.delete(0, 1);
		    		 } else if(s.charAt(0) == '.'){
		    			 
		    			 s.insert(0, "0");
		    		 }
		    	 }
		     } else if (temp.length() - posDot - 1 > mPrecision) {
		    	 
		        s.delete(posDot + mPrecision + 1, temp.length());
		     }
					tvNum.setText(s.toString);
					tvNum.setSelection(text.length());

			dataChanged(count);
		}else{
		//保留2位小數
			String text = s.toString();
			if (text.contains(".")) {
				int index = text.indexOf(".");
				if (index + 3 < text.length()) {
					text = text.substring(0, index + 3);
					tvNum.setText(text);
					tvNum.setSelection(text.length());
				}
			}
		}
		

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