一些 Java 格式化输入输出笔记

注:
       本文参考 java.util.Formatter 文档。

       Java 中常用的格式化输出函数有:printf 和 format 方法。输入输出格式以 % 开启,以转义字符结束。关于转义字符的说明见: java.util.Formatter 的文档。对于 prontf 和 format 方法,二者功能类似,但是 format 的语法格式更为严格。
       与 C 语言中的 sprintf 类似,Java 中实现字符串的格式化转换可以采用 String.format 方法。下面是结构化输出的参数格式:

  • 针对通用、字符和数组的格式为
    %[argument_index$][flags][width][.precision]conversion
  • 针对数据和时间的格式为
    %[argument_index$][flags][width]conversion
  • 针对无入参的格式输出为
    %[flags][width]conversion

       格式化数据的类型可以分为 6 类:

  • 通用类型
  • 字符
  • 数组——分为整数和浮点数
  • 时间
  • 百分数
  • 制表符

       具体控制字符以及功能如下所示:

ConversionArgument CategoryDescription
‘b’,’B’generalIf the argument arg is null, then the result is “false”. If arg is a boolean or Boolean, then the result is the string returned by String.valueOf(arg). Otherwise, the result is “true”.
‘h’,’H’generalIf the argument arg is null, then the result is “null”. Otherwise, the result is obtained by invoking Integer.toHexString(arg.hashCode()).
’s’,’S’generalIf the argument arg is null, then the result is “null”. If arg implements Formattable, then arg.formatTo is invoked. Otherwise, the result is obtained by invoking arg.toString().
‘c’,’C’characterThe result is a Unicode character
‘d’integralThe result is formatted as a decimal integer
‘o’integralThe result is formatted as an octal integer
‘x’,’X’integralThe result is formatted as a hexadecimal integer
‘e’,’E’floating pointThe result is formatted as a decimal number in computerized scientific notation
‘f’floating pointThe result is formatted as a decimal number
‘g’,’G’floating pointThe result is formatted using computerized scientific notation or decimal format, depending on the precision and the value after rounding.
‘a’,’A’floating pointThe result is formatted as a hexadecimal floating-point number with a significand and an exponent. This conversion is not supported for the BigDecimal type despite the latter’s being in the floating point argument category.
‘t’,’T’date/timePrefix for date and time conversion characters. See Date/Time Conversions.
‘%’percentThe result is a literal ‘%’ (‘\u0025’)
‘n’line separatorThe result is the platform-specific line separator

       时间格式控制字符:

ConversionFunction
‘H’Hour of the day for the 24-hour clock, formatted as two digits with a leading zero as necessary i.e. 00 - 23.
‘I’Hour for the 12-hour clock, formatted as two digits with a leading zero as necessary, i.e. 01 - 12.
‘k’Hour of the day for the 24-hour clock, i.e. 0 - 23.
‘l’Hour for the 12-hour clock, i.e. 1 - 12.
‘M’Minute within the hour formatted as two digits with a leading zero as necessary, i.e. 00 - 59.
‘S’Seconds within the minute, formatted as two digits with a leading zero as necessary, i.e. 00 - 60 (“60” is a special value required to support leap seconds).
‘L’Millisecond within the second formatted as three digits with leading zeros as necessary, i.e. 000 - 999.
‘N’Nanosecond within the second, formatted as nine digits with leading zeros as necessary, i.e. 000000000 - 999999999.
‘p’Locale-specific morning or afternoon marker in lower case, e.g.”am” or “pm”. Use of the conversion prefix ‘T’ forces this output to upper case.
‘z’RFC 822 style numeric time zone offset from GMT, e.g. -0800. This value will be adjusted as necessary for Daylight Saving Time. For long, Long, and Date the time zone used is the default time zone for this instance of the Java virtual machine.
‘Z’A string representing the abbreviation for the time zone. This value will be adjusted as necessary for Daylight Saving Time. For long, Long, and Date the time zone used is the default time zone for this instance of the Java virtual machine. The Formatter’s locale will supersede the locale of the argument (if any).
’s’Seconds since the beginning of the epoch starting at 1 January 1970 00:00:00 UTC, i.e. Long.MIN_VALUE/1000 to Long.MAX_VALUE/1000.
‘Q’Milliseconds since the beginning of the epoch starting at 1 January 1970 00:00:00 UTC, i.e. Long.MIN_VALUE to Long.MAX_VALUE.

       日期格式控制字符:

ConversionFunction
‘B’Locale-specific full month name, e.g. “January”, “February”.
‘b’Locale-specific abbreviated month name, e.g. “Jan”, “Feb”.
‘h’Same as ‘b’.
‘A’Locale-specific full name of the day of the week, e.g. “Sunday”, “Monday”
‘a’Locale-specific short name of the day of the week, e.g. “Sun”, “Mon”
‘C’Four-digit year divided by 100, formatted as two digits with leading zero as necessary, i.e. 00 - 99
‘Y’Year, formatted as at least four digits with leading zeros as necessary, e.g. 0092 equals 92 CE for the Gregorian calendar.
‘y’Last two digits of the year, formatted with leading zeros as necessary, i.e. 00 - 99.
‘j’Day of year, formatted as three digits with leading zeros as necessary, e.g. 001 - 366 for the Gregorian calendar.
‘m’Month, formatted as two digits with leading zeros as necessary, i.e. 01 - 13.
‘d’Day of month, formatted as two digits with leading zeros as necessary, i.e. 01 - 31
‘e’Day of month, formatted as two digits, i.e. 1 - 31.

       位置控制字符:

ConversionFunction
‘R’Time formatted for the 24-hour clock as “%tH:%tM”
‘T’Time formatted for the 24-hour clock as “%tH:%tM:%tS”.
‘r’Time formatted for the 12-hour clock as “%tI:%tM:%tS %Tp”. The location of the morning or afternoon marker (‘%Tp’) may be locale-dependent.
‘D’Date formatted as “%tm/%td/%ty”.
‘F’ISO 8601 complete date formatted as “%tY-%tm-%td”.
‘c’Date and time formatted as “%ta %tb %td %tT %tZ %tY”, e.g. “Sun Jul 20 16:17:00 EDT 1969”.

       Flags 和填充位

FlagGeneralCharacterIntegralFloating PointDate/TimeDescription
‘-‘yyyyyThe result will be left-justified.
‘#’y1-y3y-The result should use a conversion-dependent alternate form
‘+’--y4y-The result will always include a sign
’ ‘--y4y-The result will include a leading space for positive values
‘0’--yy-The result will be zero-padded
‘,’--y2y5-The result will include locale-specific grouping separators
‘(‘--y4y5-The result will enclose negative numbers in parentheses

1. Depends on the definition of Formattable.
2. For ‘d’ conversion only.
3. For ‘o’, ‘x’, and ‘X’ conversions only.
4. For ‘d’, ‘o’, ‘x’, and ‘X’ conversions applied to BigInteger or ‘d’ applied to byte, Byte, short, Short, int and Integer, long, and Long.
5. For ‘e’, ‘E’, ‘f’, ‘g’, and ‘G’ conversions only.

       用于控制浮点数输出格式可以采用:DecimalFormat 类来实现。具体的一个实用案例如下:

import java.text.*;

public class DecimalFormatDemo {

   static public void customFormat(String pattern, double value ) {
      DecimalFormat myFormatter = new DecimalFormat(pattern);
      String output = myFormatter.format(value);
      System.out.println(value + "  " + pattern + "  " + output);
   }

   static public void main(String[] args) {

      customFormat("###,###.###", 123456.789);
      customFormat("###.##", 123456.789);
      customFormat("000000.000", 123.78);
      customFormat("$###,###.###", 12345.67);  
   }
}

       输出为:

123456.789  ###,###.###  123,456.789
123456.789  ###.##  123456.79
123.78  000000.000  000123.780
12345.67  $###,###.###  $12,345.67
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值