社区微信群开通啦,扫一扫抢先加入社区官方微信群
社区微信群
1、C语言中可以通过输出格式说明符来控制浮点数的输出,如:%2.3f,整数位置的2表示整数部分固定以2位宽度输出,如果数据的位数小于2(且禁止输出小数的情况下,即%2.0f),则左端补以空格,否则按实际位数输出;若大于2,则按实际位数输出。小数位置的3表示输出精确到小数点后3位,如果实际小数不足3位,则在末尾补0,若大于3位,则按四舍五入取前3位。
代码如下:
#include <stdio.h>
#include <stdlib.h>
#define PI 3.1415926
#define a 314.15
int main()
{
printf("%2.0fn", PI);
printf("%2.3fn", PI);
printf("%2.3fn", a);
return 0;
}
运行结果:
2、Java中通常使用String.format()四舍五入控制精度输出,查API文档可知:
public static String format(String format, Object... args)
Returns a formatted string using the specified formatstring and arguments.
即String.format()会返回一个将参数args使用特定的格式格式化后的字符串。
代码如下:
public class Test {
public static void main(String args[]) {
System.out.println(Math.PI);
System.out.println(String.format("%.3f", Math.PI));
}
}
运行结果:
同样也可以使用java.text.DecimalFormat进行四舍五入规则化,public DecimalFormat(String pattern)
代码如下:
import java.text.DecimalFormat;
public class Test {
public static void main(String args[]) {
DecimalFormat df1 = new DecimalFormat("#.000");
DecimalFormat df2 = new DecimalFormat("0.000");
System.out.println(df1.format(0.123456)); // double型参数
System.out.println(df2.format(0.123456));
}
}
运行结果:
用#和0的唯一区别是0在数位不足时会自动补足,注意:0和#不能同时出现在小数点的同一侧。
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!