2015年3月23日星期一

Android 研發小品文 – 數字與字串的運算


巧妙的運用一些運算式簡化程式在IF-THEN上的跳躍且更顯智慧喔 ~ 但切記別用過頭讓自己邏輯大亂 !


[數字轉字串]String str = Integer.toString(i);
   反向
int I = Integer.parseInt(str);


[數字轉二進制]String str = Integer.toBinaryString(i);

[數字轉十六進制]
String str = Integer.toHexString(i);
   or
String str = Integer.toString(I, 16);
   反向
int I = Integer.parseInt(str, 16);


[ASCII轉字串]
String chStr = new Character((char)i).toString();
   反向
char ch = ‘a’;  int i = (int) ch;


[日期格式化字串]
SimpleDateFormat formatterDate = new SimpleDateFormat("yyyyMMdd");
String today = formatterDate.format(new Date());


[數字取餘數運算]
int i = j % 100;


[數字小數點後面一位取四捨五入運算]
BigDecimal bd= new BigDecimal(123.456);   
bd=bd.setScale(1, BigDecimal.ROUND_HALF_UP);// 小數後面一位, 四捨五入
int i = bd.doubleValue();


[字串合併]
String str = aStr + bStr


[字串搜尋]int i = str.indexOf(“abc”);
int i = str.lastIndexOf(“abc”);


[擷取字串]
String subStr = str.subString(from, to);


[替換字串]String repStr = str.replaceAll(“search”,”replaceBy”);

[比對字串]
int i = str.compareTo(“targetStr”);


[MATH運算單元]Math.random 返回0到1之間的一個亂數
Math.rint 求距離某數最近的整數(double)
Math.round求距離某數最近的整數(int or long)
Math.max 求兩數中最大
Math.min 求兩數中最小
Math.sqrt 求開方
Math.sqrt(x):平方根
Math.exp 求e的任意次方
Math.pow 求某數的任意次方
Math.pow(x,y):x的y次方
Math.log10 以10為底的對數
Math.log 自然對數


1 条评论: