Decima
lFor
mat类的作用是完成数字格式化的,比如应该取
几位
小数。
<span style="font-size:14px;">import java.text.DecimalFormat;
public class DecimalFormatTest001 {
public static void main(String[] args) {
DecimalFormat decimalFormat = new DecimalFormat();
decimalFormat.applyPattern("0"); // 对格式化对象使用样式,在这里的样式是只取整数部分
String string1 = decimalFormat.format(Math.PI);
System.out.println(string1);
decimalFormat.applyPattern("0.0000"); // 严格按照指定的位输出数字,不足时补零
String string2 = decimalFormat.format(Math.PI);
System.out.println(string2);
}
}</span>
或者也可以用带参数的构造函数,如下:
<span style="font-size:14px;">import java.text.DecimalFormat;
public class DecimalFormatTest002 {
public static void main(String[] args) {
//也可以创建DecimalFormat对象时,使用带参构造器,此时就不必使用applyPattern()方法了
DecimalFormat decimalFormat1 = new DecimalFormat("0");
String string1 = decimalFormat1.format(Math.PI);
System.out.println(string1);
DecimalFormat decimalFormat2 = new DecimalFormat("#.##");
String string2 = decimalFormat2.format(Math.PI);
System.out.println(string2);
}
}</span>
占位符可以使用0和#两种,当使用0的时候会严格按照样式来进行匹配,不够的时候会补0,而使用#时会将前后的0进行忽略。
ceil()和floor()函数是Math类中的两个常见函数,只是以前没有注意的是这两个函数的返回值都是double类型,以后看API要留心啦,以下是用这两个函数对Java中保留的PI值进行处理的例子:
<span style="font-size:14px;">public class Test{
public static void main(String[] args){
System.out.println("java中保留的PI值:" + Math.PI);
System.out.println("用ceil()函数处理后PI的值:" + Math.ceil(Math.PI));
System.out.println("用ceil()函数处理后-PI的值:" + Math.ceil(-Math.PI));
System.out.println("用floor()函数处理后PI的值" + Math.floor(Math.PI));
System.out.println("用floor()函数处理后-PI的值" + Math.floor(-Math.PI));
}
}</span><span style="font-size: 18px;">
</span>
程序运行结果为:
java中保留的PI值:3.141592653589793
用ceil()函数处理后PI的值:4.0
用ceil()函数处理后-PI的值:-3.0
用floor()函数处理后PI的值3.0
用floor()函数处理后-PI的值-4.0