BigDecimal,DecimalFormat,BigInteger和SimpleDateFormat
1.BigDecimal 精确浮点数运算
(1)创建对象:
BigDecimal bd = BigDecimal.valueOf(2)
(2)方法
add(BigDecimal bd) +
subtract(BigDecimal bd) -
multiply(BigDecimal bd) *
divide(BigDecimal bd) /
divide(BigDecimal bd,保留位数,舍入方式)/
byteValue() 将BigDecimal对象封装的数值转换为byte类型
shortValue()
intValue()
longValue()
floatValue()
doubleValue() //a = bd.doubleValue()获取bd对象的值赋值给double类型的a
System.out.println("输入两个数字:"); double a = new Scanner(System.in).nextDouble(); double b = new Scanner(System.in).nextDouble(); //将 a,b 封装成大数字对象 BigDecimal bd1 = BigDecimal.valueOf(a); BigDecimal bd2 = BigDecimal.valueOf(b); BigDecimal bd3; double r; //调用方法完成计算,计算结果也被封装成大数字对象 bd3 = bd1.add(bd2); r = bd3.doubleValue();//取出基本类型结果 System.out.println(a+" + "+b+" = "+r);
2. 数字格式工具将数字格式化成字符串输出
(1)创建对象:
DecimalFormat df = new DecimalFormat(格式字符)如:$###,###.000
(2)方法
format(数字)数字格式化成字符串
parse(字符串) 字符串解析成数字
applyPattern(格式字符)修改使用的格式字符
public class Test1 { public static void main(String[] args) throws ParseException { System.out.println("请输入一个数字:"); double d = new Scanner(System.in).nextDouble();//12345.123454 DecimalFormat f = new DecimalFormat("\u00A4###,###.000"); String s = f.format(d);//将数值格式化成字符串 System.out.println(s);//¥12,345.123 Number n = f.parse(s);//将字符串解析成数值 System.out.println(n);//12345.123 } }
3.BigInteger 超出长整形整数运算,使用该对象能有效防止运算溢出。
BigInteger和BigDecimal创建对象和拥有的方法类似,不在赘述。下面以一个例子来解决关于递归一文中数据溢出的问题。
原方法如下:
private static long factorial(int i) { long r = 1; if(i==0||i==1){ return r; } for(;i>0;i--){ r=r*i; } return r; }
使用BigInteger封装写法如下,并且这样计算完全不会溢出。
private static String factorial(int n) { BigInteger r = BigInteger.valueOf(1); for(int i=2;i<=n;i++){ BigInteger bd = BigInteger.valueOf(i); r = r.multiply(bd); } return r.toString(); }
4.SimpleDateFormat 格式化时间数字格式化成字符串,具体使用如下,和DecimalFormat使用语法格式上一致。
Date d1 = new Date(System.currentTimeMillis());//封装的是毫秒值,获取系统当前时间。 System.out.println(d1.getTime()); //1451236018559ms SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String s = sdf.format(d1); System.out.println(s);//2015-12-28 01:06:58 Date d2 = sdf.parse(s); System.out.println(d2.getTime());//1451236018000
(5)关于Calendar类
System.out.println("输入年月(yyyy-MM):"); String s = new Scanner(System.in).nextLine(); SimpleDateFormat f = new SimpleDateFormat("yyyy-MM"); Date d = f.parse(s); Calendar c = Calendar.getInstance(); c.setTime(d); int day = c.get(Calendar.DAY_OF_WEEK); int max = c.getActualMaximum(Calendar.DAY_OF_MONTH);