显示双精度和浮点数时,如何对齐小数点 [英] How do I align the decimal point when displaying doubles and floats

查看:164
本文介绍了显示双精度和浮点数时,如何对齐小数点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有以下小数点数:

If I have the following decimal point numbers:

Double[] numbers = new Double[] {1.1233, 12.4231414, 0.123, 123.3444, 1.1};
for (Double number : numbers) {
    System.out.println(String.format("%4.3f", number));
}

然后我得到以下输出:

1.123
12.423
0.123
123.344
1.100

我想要的是:

   1.123
  12.423
   0.123
 123.344
   1.100


推荐答案

可能有点混乱的部分是 String.format(4.3,number)

The part that can be a bit confusing is that String.format("4.3", number)

4 表示整个数字的长度(包括十进制),而不仅仅是十进制之前的部分。 3 表示小数位数。

the 4 represents the length of the entire number(including the decimal), not just the part preceding the decimal. The 3 represents the number of decimals.

所以要在十进制之前使最多4个数字的格式正确和3位小数位置所需的格式实际上是 String.format(%8.3f,number)

So to get the format correct with up to 4 numbers before the decimal and 3 decimal places the format needed is actually String.format("%8.3f", number).

这篇关于显示双精度和浮点数时,如何对齐小数点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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