1. DecimalFormat类
DecimalFormat类是 java.text包下的数字相关类
DecimalFormat is a concrete subclass of NumberFormat that formats decimal numbers. It has a variety of features designed to make it possible to parse and format numbers in any locale, including support for Western, Arabic, and Indic digits. It also supports different kinds of numbers, including integers (123), fixed-point numbers (123.4), scientific notation (1.23E4), percentages (12%), and currency amounts ($123). All of these can be localized.
本类的作用是专门负责数字的格式化和解析,需要创建对象,其有参构造器如下:
public DecimalFormat(String pattern){}
其中,pattern表示格式化模板,创建对象时应:
DecimalFormat df = new DecimalFormat("数字格式");
具体使用如下:
package number;
import java.text.DecimalFormat;
public class DecimalFormatTest01 {
public static void main(String[] args) {
DecimalFormat df = new DecimalFormat("###,###.##");
//数字格式有哪些?
/*
# 表示任意数字
, 表示千分位
. 表示小数点
0 代表位数不够时补0
###,###.##
表示加入千分位,小数点后保留两位小数
*/
//注意,SimpleDateFormat类和DecimalFormat类中的format方法都是返回字符串
String s = df.format(123456.78);
String s1 = df.format(3456.789);
System.out.println(s);"123,456.78"
System.out.println(s1);//"3,456.79"
DecimalFormat df2 = new DecimalFormat("###,###.0000");//保留四位小数,小数位不够时自动补0
String s2 = df2.format(1234.56);
System.out.println(s2);//"1,234.5600"
}
}
2. BigDecimal类
- BigDecimal类属于大数据,是引用类型不是基本数据类型。属于 JAVA 对象!
- 这是SUN提供的一个类,专门用在财务软件中!
简单介绍一下怎么使用:
package number;
import java.math.BigDecimal;
public class BigDecimalTest01 {
public static void main(String[] args) {
//这个100不是普通的100,是精度极高的100
BigDecimal bd = new BigDecimal(100);
//精度极高的200
BigDecimal bd2 = new BigDecimal(200);
//BigDecimal类下的一些方法:
//求和
//注意,BigDecimal 定义的数据都是引用数据类型,不能直接bd + bd2
//可以调用方法求和
BigDecimal bigDecimal = bd.add(bd2);
System.out.println(bigDecimal);//精度极高的300
//调用除法
BigDecimal bigDecimal2 = bd2.divide(bd);
System.out.println(bigDecimal2);//精度极高的2
}
}