格式化具有相同填充量的数字 [英] Formatting numbers with same amount of padding

查看:90
本文介绍了格式化具有相同填充量的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Java中格式化3位浮点数,使它们垂直排列,使它们看起来像:

I want to format 3 digit floats in Java so they line up vertically such that they look like:

123.45
 99
 23.2
 45

当我使用DecimalFormat类时,我得到关闭,但我想在项目有1或2位数时插入空格。

When I use DecimalFormat class, I get close, but I want to insert spaces when the item has 1 or 2 digits.

我的代码:

DecimalFormat formatter = new java.text.DecimalFormat("####.##");
float [] floats = [123.45, 99.0, 23.2, 45.0];

for(int i=0; i<floats.length; i++)
{
    float value = floats[i];

    println(formatter.format(value));
}

它产生:

123.45
99
23.2
45

如何打印它以使除第一行以外的所有行都移位1个空格?

How can I print it so that all but the first line is shifted over by 1 space?

推荐答案

尝试使用 String.format() JavaDoc ):

public static void main(String args[]){
  String format = "%10.2f\n";  // width == 10 and 2 digits after the dot
  float [] floats = {123.45f, 99.0f, 23.2f, 45.0f};
  for(int i=0; i<floats.length; i++) {
      float value = floats[i];
      System.out.format(format, value);
}

,输出为:

123.45
 99.00
 23.20
 45.00

这篇关于格式化具有相同填充量的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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