使用Java时小数位数过多? [英] Too many decimal places when using Java?

查看:55
本文介绍了使用Java时小数位数过多?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试将我的程序四舍五入到小数点后两位.但似乎无法.这是我的代码:

I am currently trying to get my program to round to 2 decimal places, but seem to be unable to. Here is my code:

double ounce;
double grams; 
grams = 0.00;
System.out.println("This programme will print a table that can be used to convert ounces to grams, from values 1-15.");
System.out.println("One ounce is equal to 28.35 grams.\n\nOunces \t\t\t Grams");

ounce = 0;
do {
  ounce++;
  grams+=28.35;
  System.out.println((""+ounce+"\t\t\t"+grams+""));
} while (ounce <15);

输出看起来像这样:

    Ounces           Grams
1.0                  28.35
2.0                  56.7
3.0                 85.05000000000001
4.0                  113.4
5.0                  141.75
6.0                  170.1
7.0                  198.45
8.0                  226.79999999999998
9.0                 255.14999999999998
10.0                 283.5
11.0                311.85
12.0                340.20000000000005
13.0                368.55000000000007
14.0                 396.9000000000001
15.0            425.2500000000001

最后,我在克"下的数字未完全正确对齐.有什么想法可以使它们完美对齐吗?

Lastly, my numbers under "grams" are not aligning exactly proper. Any ideas how to get them to align perfectly?

推荐答案

您可以使用其他输出方法,如下所示:

You can use a another output method like this:

           System.out.format("%f%5f\n",ounce, gramsFormated);

您可以决定想要的宽度.在此示例中为5.

You can decide how you want your width. In this example it is 5.

这篇关于使用Java时小数位数过多?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆