Calendar类的用法以及利用round() 四舍五入的小技巧

通过下面代码简单了解一下Calendar类的用法。注意:Calendar.MONTH 是从0开始的

import java.util.Calendar;

public class CalendarTest {

	public static void main(String[] args) {
		Calendar cal = Calendar.getInstance();
		StringBuffer str = new StringBuffer();
		str.append(cal.get(Calendar.YEAR)).append("年");
		str.append(cal.get(Calendar.MONTH)+1).append("月");
		str.append(cal.get(Calendar.DAY_OF_MONTH)).append("日");
		str.append(cal.get(Calendar.HOUR_OF_DAY)).append("时");
		str.append(cal.get(Calendar.MINUTE)).append("分");
		str.append(cal.get(Calendar.SECOND)).append("秒");
		str.append(cal.get(Calendar.MILLISECOND)).append("毫秒");
		System.out.println(str);
	}

}

输出 :2018年5月18日22时27分55秒758毫秒


        在Math类中有一个方法round(),实现四舍五入,但是只能保留整数,下面通过定义MyMath类来实现任意位数的四舍五入,注意观察两种round(0函数的区别

package shi;

import java.util.Calendar;

class MyMath {
	/*
	 * 实现数字的四舍五入操作
	 * @param num 要四舍五入的数字
	 * @param n 要保留的位数
	 */
	public static double round(double num,int n) {
		return Math.round(num*Math.pow(10.0, n))/Math.pow(10.0, n);
	}
	
}
public class RoundTest {
	
	public static void main(String[] args) {
		
		System.out.println(Math.round(10.222));
		System.out.println(Math.round(10.827));
		System.out.println("===========================");
		System.out.println(MyMath.round(10.222,2));
		System.out.println(MyMath.round(10.827,2));
		
	}

}
输出: 10
           11
           ===========================
           10.22
           10.83


猜你喜欢

转载自blog.csdn.net/bingocoder/article/details/80370238
今日推荐