Android 數值型字串,轉化保留兩位小數

2021-08-14 19:21:26 字數 2602 閱讀 9559

**:

string s = "12345.67890";

float f= float.parsefloat(s);

decimalformat decimalformat=new decimalformat(".00");//構造方法的字元格式這裡如果小數不足2位,會以0補足.

string p=decimalformat.format(f);//format 返回的是字串

p值 : 12345.68

edittext輸入**,保留兩位小數,最大**小於10萬,**:

方法一

/**

* 設定限制小數點最多兩位,最大5位數

*/public void setpricepoint(final edittext edittext) else

}else if (posdot>5)

if (temp.length() - posdot - 1 > 2)//如果包含小數點

if (s.tostring().contains("."))

}if (s.tostring().trim().substring(0).equals("."))

if (s.tostring().startswith("0") && s.tostring().trim().length() > 1) }}

@override

public void beforetextchanged(charsequence s, int start, int count, int after)

@override

public void aftertextchanged(editable s)

});// edittext.addtextchangedlistener(new textwatcher() else

// }else

// if (temp.length() - posdot - 1 > 2)//如果包含小數點

// else

// log.e("feifei",edittext.gettext().tostring()+"aaaaa");

//// }else

//// if (s.tostring().contains(".")) else

// log.e("feifei",edittext.gettext().tostring()+"aaa");

////

// }

// }

// if (s.tostring().trim().substring(0).equals(".")) else

//// if (s.tostring().startswith("0") && s.tostring().trim().length() > 1) else

// }

// }

//// @override

// public void beforetextchanged(charsequence s, int start, int count, int after)

//// @override

// public void aftertextchanged(editable s)

//// });

}

方法二(正則語句):

private boolean isright(charsequence charsequence)||\\d+\\.||\\d+\\.+\\d$";//非零開頭的最多帶兩位小數的數字

// string reg = "^[0-9]+(.[0-9])?$";

pattern pattern = pattern.compile(reg);

matcher matcher = pattern.matcher(charsequence);

boolean b = matcher.matches();

return b;

}private void setaddtextchangewithedittext(final edittext edittext)else

}@override

public void ontextchanged(charsequence charsequence, int i, int i1, int i2)

boolean b = isright(charsequence) ;

if (b==true)else else }}

@override

public void aftertextchanged(editable editable)

});}

字串轉化為數值

工作時遇到這樣的乙個情況 伺服器a向b傳送請求並接受結果,耗時300ms,伺服器b從接受請求到傳送完畢,耗時100ms。由於是內網,不可能有200ms的網路延遲。後經檢測,是因為傳輸時用的是字串格式,解析時用了sscanf造成的。由於sscanf要考慮到變參問題,並且接受的種類更加豐富 相對於str...

字串轉化為整數值

思路分析 首先判斷字串是否為空,返回0 考慮前面的是否是空格,使用trim 去掉,然後判斷長度是否為0,是的話,返回0 判斷第乙個字元是不是 和 設定變數sign記錄 迴圈取得字串的數字,考慮字串中有非數字,遇到就退出,保留前面的數字 考慮溢位的情況,溢位返回integer的最大值或最小值 publ...

Android字串轉化方法

將unicode字串轉換成bool型陣列 public boolean strtobool string input 將bool型陣列轉換成unicode字串 public string booltostr boolean input 將字串轉換成二進位制字串,以空格相隔 private strin...