常用API学习08(Java)
格式化
格式化指的是将数据按照指定的规则转化为指定的形式 。
那么为什么需要格式化?格式化有什么用?
以数字类为例,假设有一个比分牌,在无人得分的时候我们希望以:“00:00”的形式存在,那么靠计算机默认的格式肯定是不行的,所以要给其进行格式化。
DecimalFormat:数字格式化的类,可以指定保留的小数位,在使用的时候需要注意其中0和#的区别。
写一个案例:
package com.itheima.date;import java.text.DecimalFormat;public class DecimalFormatDemo {public static void main(String[] args) {//表示数字强制保留两位小数//0表示强制保留 #表示有保留//DecimalFormat df=new DecimalFormat("0.00");//DecimalFormat df=new DecimalFormat("0.0#");//DecimalFormat df=new DecimalFormat("0.##");//整数位保留至少两位,小数必须保留2位DecimalFormat df=new DecimalFormat("00.00");//00.00 #0.00 #.0 00.## 00.0#//整数位,如果有#,则#一定是放在0之前的,或者#.xxx//小数位,如果有#,则一定放在0之后,或者xxx.#String f = df.format(1.2);System.out.println(f);String f2 = df.format(4.20);System.out.println(f2);String f3 = df.format(4.1);System.out.println(f3);}
}
接下来一次试,首先是:
DecimalFormat df=new DecimalFormat("00.00");
运行一下:
然后是:
DecimalFormat df=new DecimalFormat("00.0#");
运行:
我们会发现,如果指定为“0”,那么就会强制保留这个“0”,如果是“#”,则不会保留这个“0” 。
SimpleDateFormat:对日期进行格式化的类,将指定形式的字符串转化为日期对象,也可以将日期对象转为字符串对象。
package com.itheima.format;import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;public class SimpleDateFormatDemo {public static void main(String[] args) throws ParseException {//将字符串转换为date类型String s1 = "2023-07-19";//构建格式化对象SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");Date d1 = sdf.parse(s1);System.out.println(d1);//将日期类转为字符串类型Date d2 = new Date();SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");String s2 = sdf2.format(d2);System.out.println(s2);}
}