如何在Java中将数字格式化为固定长度,带空格,千位分隔符,2个小数 [英] How to format a number to Fixed length, space padded, thousand separator, 2 decimals in Java
本文介绍了如何在Java中将数字格式化为固定长度,带空格,千位分隔符,2个小数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Java中,如何将数字格式化为固定长度的空格,并在左字符串上填充空格,该空格为千位分隔符,在Java中小数点后两位. (比方说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);
但是,如果您不担心使用(空格)作为分组分隔符,则可以简单地做到这一点:
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
这篇关于如何在Java中将数字格式化为固定长度,带空格,千位分隔符,2个小数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文