java的格式化
最近做题,总是遇到格式化问题,就想着总结一下,方便以后查阅。我大致总结了一下,如下:
方法1
这是最简单的一种方法,就是直接使用printf函数,具体操作和C语言中的格式化相同。
首先,我们先总结一下格式类型:
转换符 | 说明 |
%d | 十进制整数类型 |
%x | 十六进制整数类型 |
%o | 八进制整数类型 |
%b | 布尔类型(true或者false) |
%f | 浮点数类型 |
%s | 字符串类型 |
%c | 字符类型 |
%% | 百分比类型(%) |
%n | 换行符 |
不过需要注意一点:最后的结果是四舍五入后的。
下面,给个代码示例:
package homework;
public class qw {
public static void main(String[] args) {
double d = 33.1415926;
String s = "hello";
int i = 1314;
// "%"表示进行格式化输出,"%"之后的内容为格式的定义。
System.out.printf("%f%n", d);
System.out.printf("%8.3f%n", d);// "9.2"中的9表示输出的长度,2表示小数点后的位数。
System.out.printf("%+8.3f%n", d);// "+"表示输出的数带正负号。
System.out.printf("%-8.4f%n", d);// "-"表示输出的数左对齐(默认为右对齐)。
System.out.printf("%+-8.3f%n", d);// "+-"表示输出的数带正负号且左对齐。
System.out.printf("%d%n", i);
System.out.printf("%o%n", i);
System.out.printf("%x%n", i);
System.out.printf("%#x%n", i);//带十六进制标志的十六进制数
System.out.printf("%s%n", s);
}
}
运行结果如下:
方法2
使用十进制数字格式化(DecimalFormat),java提供了DecimalFormat类来帮助我们轻松的实现十进制数字的格式化。开头需要加上: import java.text.DecimalFormat; 不过该方法也有四舍五入现象的存在。
DecimalFormat类主要依靠“0”和“#”占位符来指定数字长度,其中,两种占位符的用法如下:
(1)“0”:表示当位数不足时,用“0”补位,若是位数足够,显示正常位数;
(2)“#”:与“0”不同,表示当位数不够时,该位不显示。
使用DecimalFormat类进行格式化的时候,需要先定义一个对象,然后使用该对象调用format函数。
下面,我们举个例子看看:
package homework;
import java.text.DecimalFormat;
public class qw {
private static double a = 3.14;
private static double b = a;
public static void main(String[] args) {
DecimalFormat df = new DecimalFormat("###.####");
System.out.println(df.format(a));
DecimalFormat d = new DecimalFormat("000.0000");
System.out.println(d.format(b));
}
}
运行结果如下:
方法3
使用String.format()方法,其形式和方法1中的printf很相似,该法也存在四舍五入的问题。
package homework;
public class qw {
private static double a = 3.1415926;
public static void main(String[] args) {
System.out.println(String.format("%.2f",a));
}
}
运行结果如下:
方法4
使用Formatter类,我们需要引入类名:java.util.Fomatter,具体写法和方法1的printf是一样的。
下面,我们举个例子:
package homework;
import java.util.Formatter;
public class qw {
public static void main(String[] args){
double a=3.1415926;
Formatter formatter = new Formatter(System.out);
formatter.format("%.2f",a);
formatter.close();
}
}
注意:
在例子中,我直接使用了Formatter formatter = new Formatter(System.out);也就是指定了输出,控制台会将其中的对象输出,当然也可以不这么写,再以后添加对象时,使用System.out.print(formatter());输出。还有就是最后要添加formatter.close();目的是为了防止该格式持续下去,对以后的输出造成影响。
即:
package homework;
import java.util.Formatter;
public class qw {
public static void main(String[] args){
double a=3.1415926;
Formatter formatter = new Formatter();
System.out.println(formatter.format("%.2f",a));
formatter.close();
}
}
运行结果如下:
总结
格式化是编程中经常遇到的问题,尤其是精度问题,很多平台上,如果答案精度不对,会显示答案错误,当我们掌握了多种格式化的方法后,就不用担心这个问题了。