在java中显示小数点

时间:2014-12-27 07:17:11

标签: java

int a = 91000;
int b = Math.pow(100,2);
float ans = (float) a/b;
ans=9.1

我希望输出正确到小数点后的6位数,即

ans =9.100000

我怎么能在java中做到这一点?

6 个答案:

答案 0 :(得分:1)

您可以使用printf方法:

System.out.printf("%.6f", val);

%.6f语法告诉Java将您的变量返回到带有6位小数的浮点数

答案 1 :(得分:1)

您可以使用DecimanlFormat

ans=9.1
System.out.println(new DecimalFormat("#0.000000").format(ans));

输出

9.100000

有关DecimalFormat访问this链接的更多信息。

答案 2 :(得分:0)

使用下面的代码将float转换为字符串,在您提供要提供的小数位数后的点: String.format("%.6f", ans)

查看文档,了解更多格式:http://docs.oracle.com/javase/8/docs/api/java/util/Formatter.html#syntax

答案 3 :(得分:0)

您可以使用doubleformatted output。像,

int a = 91000;
double b = Math.pow((double) 100, 2);
double ans = a / b;
System.out.printf("%.6f%n", ans);

输出

9.100000

答案 4 :(得分:0)

您可以使用String.format来定义您喜欢的输出,例如

String.format("Range = %.6f", range)

显示6位小数。

答案 5 :(得分:0)

最简单的解决方案是编写类似

的内容
int a = 91000
System.out.println(a / 1e4); // there is only 4 decimal places possible

或者强制它达到6位精度

System.out.printf("%,6f%n", a / 1e4);
相关问题