0
点赞
收藏
分享

微信扫一扫

Java中数字格式化format方法

年夜雪 2022-02-15 阅读 146


如果是一个浮点类型的数字,想要保留指定的位数输出,则可以:

DecimalFormat类

保留两位小数,这里的0是占一个字符,不足的补0,点是小数分隔符。

DecimalFormat decimalFormat1 = new DecimalFormat(".00");
DecimalFormat decimalFormat2 = new DecimalFormat(".00%");

System.out.println(decimalFormat1.format(12.7));// 12.70
System.out.println(decimalFormat2.format(0.7));// 70.00%

String类的format()方法 

public class Main {
public static void main(String[] args) {
String s = String.format("%.2f", 3.1415926);
System.out.println(s);// 3.14
}
}

如果想要数字和字符混合输出,则可以:

public class Main {
public static void main(String[] args) {
String s = String.format("%d斤水果是%.2f元", 3, 10.5692);
System.out.println(s);// 3斤水果是10.57元
}
}

如果在格式化模式需要%的输出,则可以:

public class Main {
public static void main(String[] args) {
String s = String.format("%d%%", 90);
System.out.println(s);// 90%
}
}

如果想要格式化整数,这里的整数包含byte、Byte、short、Short、int、Integer、long和Long


%d:将值格式化为十进制

%o:将值格式化为八进制

%x:将值格式化为小写十六进制

%X:将值格式化为大写十六进制


public class Main {
public static void main(String[] args) {
String s = String.format("%d %o %x %X", 255, 255, 255, 255);
System.out.println(s);// 255 377 ff FF
}
}

如果想要设置某个数字所占的宽度,则可以

public class Main {
public static void main(String[] args) {
String s = String.format("%8d", 255); //所占宽度是8列,不足八列右对齐
String s1 = String.format("%-8d", 255); //所占宽度是8列,不足八列左对齐
System.out.println(s);// 255
System.out.println(s1);// 255
}
}

如果想要格式化浮点数float、Float、double、Double,可以使用%f、%e和%E


%f:将值格式化为十进制浮点数,小数点默认保留6位

%e:将值格式化为科学计数法的十进制浮点数,用小写e表示次幂

%e:将值格式化为科学计数法的十进制浮点数,用大写E表示次幂


public class Main {
public static void main(String[] args) {
String s = String.format("%f %e %E", 123.456, 123.456, 0.456);
System.out.println(s);// 123.456000 1.234560e+02 4.560000E-01
}
}

当然也可以指定保留小数点位数

public class Main {
public static void main(String[] args) {
String s = String.format("%.2f %.1e %.3E", 123.456, 123.456, 0.456);
System.out.println(s);// 123.46 1.2e+02 4.560E-01
}
}

同样的也可以设置它们的宽度

public class Main {
public static void main(String[] args) {
String s = String.format("%15f", 1.456);
System.out.println(s);// 1.456000
}
}



举报

相关推荐

0 条评论