固定长度。空间spadded,千位分隔符,Java中的2位小数值格式 [英] Fixed length. space spadded, thousand seperator, 2 decimal places number value format in Java

查看:136
本文介绍了固定长度。空间spadded,千位分隔符,Java中的2位小数值格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将数字格式化为固定长度,空格填充在左侧字符串上,空格为千位分隔符,Java中有2个小数位?
(比方说14个字符串)

How to format a number into a fixed-length, space padded on left string with space as thousand seperator with 2 decimal places in Java? (let's say 14 characters string)

Number = 10.03 must be "         10.03" and  
Number 1235353.93 must be   "  1 235 353.93".


推荐答案

DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setGroupingSeparator(' ');
DecimalFormat format = new DecimalFormat("#,###.00", symbols);

System.out.format("%14s\n", format.format(1235353.93));
System.out.format("%14s\n", format.format(10.03));

以上打印在我的机器上:

The above prints below on my machine:

  1 235 353.93
         10.03

你可以如果要将结果存储到变量中,也可以使用 String.format

You can also use String.format if you want to store the result into a variable:

String formatted = String.format("%14s", format.format(1235353.93));

System.out.println("Formatted Number is " + formatted);

但是,如果你不想使用 (space)作为分组分隔符,你可以简单地完成这个:

However, if you weren't bothered about using (space) as the grouping separator, you could've simply done this:

String.format("%,14.2f", 234343.34);

将打印:

    234,343.34

这篇关于固定长度。空间spadded,千位分隔符,Java中的2位小数值格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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