java中的数字格式化

Formatting a Number Using a Custom Format
A pattern of special characters is used to specify the format of the number. This example

demonstrates some of the characters. For a complete listing, see the javadoc documentation for

the DecimalFormat class.
There is no symbol that either displays a digit(阿拉伯数字) or a blank if no digit present.

Hence, it is not possible to format a number so that it will have a specific width. To achieve a

specific width, you must manually pad the formatted number.
数据的格式化输出
    // The 0 symbol shows a digit or 0 if no digit present
    NumberFormat formatter = new DecimalFormat("000000");
    String s = formatter.format(-1234.567);  // -001235
    // notice that the number was rounded up
 
    // The # symbol shows a digit or nothing if no digit present
    formatter = new DecimalFormat("##");
    s = formatter.format(-1234.567);         // -1235
    s = formatter.format(0);                 // 0
    formatter = new DecimalFormat("##00");
    s = formatter.format(0);                 // 00
   
    // The . symbol indicates the decimal point
    formatter = new DecimalFormat(".00");
    s = formatter.format(-.567);             // -.57
    formatter = new DecimalFormat("0.00");
    s = formatter.format(-.567);             // -0.57
    formatter = new DecimalFormat("#.#");
    s = formatter.format(-1234.567);         // -1234.6
    formatter = new DecimalFormat("#.######");
    s = formatter.format(-1234.567);         // -1234.567
    formatter = new DecimalFormat(".######");
    s = formatter.format(-1234.567);         // -1234.567
    formatter = new DecimalFormat("#.000000");
    s = formatter.format(-1234.567);         // -1234.567000
   
   
    // The , symbol is used to group numbers
    formatter = new DecimalFormat("#,###,###");
    s = formatter.format(-1234.567);         // -1,235
    s = formatter.format(-1234567.890);      // -1,234,568
   
    // The ; symbol is used to specify an alternate pattern for negative values
    formatter = new DecimalFormat("#;(#)");
    s = formatter.format(-1234.567);         // (1235)
   
    // The ' symbol is used to quote literal symbols
    formatter = new DecimalFormat("'#'#");
    s = formatter.format(-1234.567);         // -#1235
    formatter = new DecimalFormat("'abc'#");
    s = formatter.format(-1234.567);         // -abc1235
 总结:
1  如果用0充当格式化符号,不足时候补零
2 如果用#充当格式化符号,不足时候什么都不加
3 小数点后的格式化符号都支持保留小数位的控制
4 可用单引号添加文本  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值