classMathUtil{ /** * * @param d 要四舍五入的数 * @param n 要保留的小数位 * @return 四舍五入的结果 */ publicstaticdoubleround(double d,int n){ d *= Math.pow(10,n); d = Math.round(d); d /= Math.pow(10,n); return d; } privateMathUtil(){}
}
publicclassMathDemo{ publicstaticvoidmain(String[] args){ double a = 19.26731; System.out.println(Math.round(a)); a = MathUtil.round(a,2); System.out.println(a); } }
Random类
public int nextInt(int bound)产生一个不大于边界的随机的非负整数
1 2 3 4 5 6 7 8 9 10 11 12 13
package demo08;
import java.util.Random;
publicclassRandomDemo{ publicstaticvoidmain(String[] args){ Random r = new Random(); for (int i = 0; i < 10; i++) { System.out.println(r.nextInt(100)); } } }
42 79 60 46 67 50 83 51 37 15
具体还有很多方法
BigInteger和BigDecimal
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
package demo08;
import java.math.BigInteger;
publicclassJavaAPIDemo{ publicstaticvoidmain(String[] args){ BigInteger A = new BigInteger("123131231220412049812312"); BigInteger B = new BigInteger("1231231412"); System.out.println("+:"+A.add(B)); System.out.println("-:"+A.subtract(B)); System.out.println("*:"+A.multiply(B)); System.out.println("/:"+A.divide(B));
}
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14
package demo08;
import java.math.BigInteger;
publicclassJavaAPIDemo{ publicstaticvoidmain(String[] args){ BigInteger A = new BigInteger("123131231220412049812312"); BigInteger B = new BigInteger("1231231412"); BigInteger[] result = A.divideAndRemainder(B); System.out.println("商:"+result[0]+" 余:"+result[1]);
}
}
商:100006570674150 余:553412512
BigDecimal与BigInteger类似。
Date
1 2 3 4 5 6 7 8 9 10 11 12 13
package demo08;
import java.util.Date;
publicclassJavaAPIDemo{ publicstaticvoidmain(String[] args){ Date d = new Date(); System.out.println(d);
}
}
通过观察Date类构造器可以发现,Date类只是对long数据的一种包装。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
package demo08;
import java.util.Date;
publicclassJavaAPIDemo{ publicstaticvoidmain(String[] args){ Date d = new Date(); long current = d.getTime(); current += 864000000;//10天的毫秒数 Date e = new Date(current); System.out.println(e); }
publicclassJavaAPIDemo{ publicstaticvoidmain(String[] args){ Date d = new Date(); SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss SSS"); String str = s.format(d); System.out.println(str); }