背景
在專案中經常會遇到百分比,平均值,平均耗時之類的計算,這些值在前端展示的時候往往要求固定的格式,這個時候該如何做呢?
常用的格式示例
DecimalFormat格式化浮點數 public static void decimalFormat() { DecimalFormat format=new DecimalFormat("0"); System.out.println(format.format(230.33f)); Float ww=(0.0f-0.4f)/0.4f; System.out.println(format.format(ww));
結果:
230-1
NumberFormat格式化
public static void percentFormat() { NumberFormat nf=NumberFormat.getPercentInstance(); System.out.println(nf.format(3.52)); }
列印結果:
35%
String格式化
public static void stringFormat() { System.out.println(String.format("%s,%f", 1,1.0f)); }
結果:
1,1.000000
時間格式化
public static void dateFormat() { SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd"); System.out.println(sdf.format(new Date())); }
結果:
20210122
MessageFormat格式化
public static void messageFormat() { String msg = "歡迎光臨,當前({0})等待的業務受理的顧客有{1}位,請排號辦理業務!"; MessageFormat mf = new java.text.MessageFormat(msg); String fmsg = mf.format(new Object[]{new Date(),3}); System.out.println(fmsg); }
結果
public static void choiceFormat() { double[] limits = {1,2,3,4,5,6,7}; String[] dayOfWeekNames = {"Sun","Mon","Tue","Wed","Thur","Fri","Sat"}; ChoiceFormat form = new ChoiceFormat(limits, dayOfWeekNames); ParsePosition status = new ParsePosition(0); for (double i = 0.0; i <= 8.0; ++i) { status.setIndex(0); System.out.println(i + " -> " + form.format(i) + " -> " + form.parse(form.format(i),status)); } }
結果:
0.0 -> Sun -> 1.01.0 -> Sun -> 1.02.0 -> Mon -> 2.03.0 -> Tue -> 3.04.0 -> Wed -> 4.05.0 -> Thur -> 5.06.0 -> Fri -> 6.07.0 -> Sat -> 7.08.0 -> Sat -> 7.0
總結
java 提供了格式化的功能,java.text包下提供了很多格式化的方式,值得深入瞭解一下。
最新評論