[英]Using string format to add dollar sign and commas to my numbers
I'm relatively new to Java, and I have a line of code I'm struggling with: 我是Java的新手,我有一系列我正在努力的代码:
System.out.println(String.format("%-14s%10.2f","Income",income));
I would like to add a $ and commas to the income, but whenever I try to add it in the line, I get errors or the $ shows up in the wrong spot. 我想在收入中添加$和逗号,但每当我尝试将其添加到行中时,我会收到错误或$出现在错误的位置。
So currently it prints: 所以目前它打印:
Income 50000.00
but I would like it to print: 但我想要打印:
Income $50,000.00
If there is a way to add these additions while keeping 'Income' and the digits nicely spaced apart, that'd be preferred. 如果有一种方法可以在保持“收入”和数字间隔很大的情况下添加这些添加项,那么这将是首选。 :)
:)
If you wish to display $ amount in US number format than try: 如果您希望以美国数字格式显示$ amount,请尝试:
DecimalFormat dFormat = new DecimalFormat("####,###,###.##");
System.out.println("$" + dFormat.format(income));
You should use decimal format
and format the number. 您应该使用
decimal format
并格式化数字。
DecimalFormat formatter = new DecimalFormat("#,###,###");
String yourFormattedString = formatter.format(100000);
System.out.println("$" + yourFormattedString);
The result will be 结果将是
-> 1,000,000 for 1000000
-> 10,000 for 10000
-> 1,000 for 1000
Solution with String.format
only: 仅限
String.format
解决方案:
System.out.println(String.format("%-14s$%,.2f","Income",50000.));
it will print Income $50,000.00
它将打印
Income $50,000.00
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.