java - 如何打印最后带有数字的语句,但将数字从右到左设置为一定长度?
问题描述
我对编码很陌生,除了简单的格式和布尔语句之外,我什么都不知道。我要打印的是:
Gross Pay: $ 0.00
我的代码是:
System.out.printf("Gross Pay: " + "$" + "%.2f\n", grossPay);
输出是
Gross Pay: $0.00
我相信我想以 7 个空格长度从右到左打印。我该怎么做?
编辑:对不起,我没有更具体。我没有必要问它是否有效,但我问的是如何让它Gross Pay: $ 0.00
与空间和所有东西完全一致。我的实际问题是如何获得$ 0.00
$ 和 0.00 之间的空间 3 是自动的,而不是仅仅做+ " " +
.
解决方案
像这样的东西应该可以工作(已编辑):
String.format("%7.2f", value)
样本:
System.out.println("Gross Pay: $" + String.format("%7.2f", 10.01));
System.out.println("Gross Pay: $" + String.format("%7.2f", 100.01));
System.out.println("Gross Pay: $" + String.format("%7.2f", 1000.01));
System.out.println("Gross Pay: $" + String.format("%7.2f", 10000.01));
样本输出:
Gross Pay: $ 10.01
Gross Pay: $ 100.01
Gross Pay: $1000.01
Gross Pay: $10000.01
作为使用空格的替代方法,这是一个带有数字填充的示例:
DecimalFormat currency = new DecimalFormat();
currency.setGroupingUsed(false);
currency.setMinimumIntegerDigits(12);
currency.setMaximumIntegerDigits(12);
currency.setMinimumFractionDigits(2);
currency.setMaximumFractionDigits(2);
currency.setDecimalSeparatorAlwaysShown(true);
System.out.println("Gross Pay: $" + currency.format(939394.02480240));
推荐阅读
- crdt - 如何在 delta-crdt 中管理和保持 delta-state 的大小最小
- c++ - 使用 max 函数和/或替代方法的正确方法
- typescript - 单击按钮共享时未加载社交共享
- python - 带有捕获组的 Python 正则表达式可选组不起作用
- javascript - Cloud Functions 中的 Firestore:文档删除是异步的吗?
- django - params={'value': value}, django.core.exceptions.ValidationError: ["'' value 必须是 True 或 False。"]
- javascript - 尝试进行身份验证时出现 react-aad-msal 无限循环错误
- arrays - 当切片的最大长度小于底层数组的长度时,切片的“动态大小”一词如何合理?
- bash - makefile 中的主机名操作
- python - 我如何打印 10 个输入?