【464-465】数字类
2022-01-24 18:59:00 # JavaSE

数字格式化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import java.text.DecimalFormat;

public class _464_数字格式化 {
public static void main(String[] args) {
// DecimalFormat 专门负责数字格式化
/*
数字格式:
# 代表任意数字
, 代表千分位
. 代表小数点
0 代表不够时补 0
*/
// 这里表示 加入千分位 保留两位小数
DecimalFormat decimalFormat = new DecimalFormat("###,###.##");
String format = decimalFormat.format(123123.126);
System.out.println(format); // 123,123.13

DecimalFormat decimalFormat1 = new DecimalFormat("###,###.0000");
String format1 = decimalFormat1.format(123123.126);
System.out.println(format1); // 123,123.1260

DecimalFormat decimalFormat2 = new DecimalFormat("###,###.####");
String format2 = decimalFormat2.format(123123.123);
System.out.println(format2); // 123,123.123

}
}

高精度BigDecimal

不属于基本数据类型,属于引用数据类型
用于财务软件中,double不够用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import java.math.BigDecimal;

public class _465_高精度BigDecimal {
public static void main(String[] args) {
BigDecimal bigDecimal = new BigDecimal(100);
BigDecimal bigDecimal1 = new BigDecimal("123");
BigDecimal bigDecimal2 = new BigDecimal(123.33);

// 求和
BigDecimal add = bigDecimal.add(bigDecimal1);
System.out.println(add);

// 除法
BigDecimal divide = bigDecimal1.divide(bigDecimal);
System.out.println(divide);
}
}

Prev
2022-01-24 18:59:00 # JavaSE
Next