[Java]型態轉換

  • 888
  • 0
  • 2022-08-22

Java型態轉換

# BigDecimal
DecimalFormat df = new DecimalFormat("#0.00");
System.out.println(df.format(0.7)); //0.70

DecimalFormat df = new DecimalFormat();

df.applyPattern("#.##");
System.out.println(df.format(123456.0)); //零不呈顯123456

df.applyPattern("0.00");
System.out.println(df.format(123456.0));// 零呈顯123456.00

df.applyPattern("-0.00");
System.out.println(df.format(123456.34567));// -123456.35

df.applyPattern("-0,000.00");
System.out.println(df.format(123456.34567));// -123,456.35 逗號

df.applyPattern("0.00%");
df.applyPattern("0.00 KG");

// 除加減乘
gainLoss.divide(帶入數值,幾位數,BigDecimal.ROUND_HALF_UP); //四舍五入
add、subtract、multiply

// Sample
BigDecimal gainLossPercent = gainLoss.divide(cost,3,BigDecimal.ROUND_HALF_UP);
BigDecimal costTotal = cost1.add(cost2);

// to String
String.valueOf(costTotal));

# 日期與字串互轉
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm"); //設定日期格式
String dateString = df.format(date); //字串轉日期
Date dates = df.parse("2022-04-07 23:50"); //日期轉字串