java 格式化2位小数_在Java中格式化为2个小数位 (Formatting to 2 decimal places in Java)...

First of all, %s means string, and %f means float number.

System.out.printf("%-40s %-6.2f", "Borrowing Fee: $", borrowingFee + "\n");

In your case, the 3rd argument, borrowingFee + "\n", creates a string, which couldn't match up with %f. Which is why you might get the exception message java.util.IllegalFormatConversionException: f != java.lang.String

Here the IllegalFormatConversionException indicates that f(%f) is incompatible with java.lang.String.

The simple fix is moving the \n into the 1st argument, since it's the format:

System.out.printf("%-40s %-6.2f\n", "Borrowing Fee: ", borrowingFee);

Notice that the first argument "%-40s %-6.2f\n" is the format that creates blanks with %s and %f, and the rest arguments are the fillings for those blanks.

In addition, your 2nd argument, "Borrowing Fee: $", is promised to be a fixed string. Unless you want a giant space between the colon and the number like Borrowing Fee: 55.00, you don't need to format it. You can simply do

System.out.printf("Borrowing Fee: %.2f\n", borrowingFee);

or slightly larger space with \t

System.out.printf("Borrowing Fee:\t %.2f\n", borrowingFee);

printf on docs.oracle.com (java7):

public PrintStream printf(String format,

Object... args)

Parameters:

format - A format string as described in Format string syntax

args - Arguments referenced by the format specifiers in the format string. If there are more arguments than format specifiers, the extra arguments are ignored. The number of arguments is variable and may be zero. The maximum number of arguments is limited by the maximum dimension of a Java array as defined by The Java™ Virtual Machine Specification. The behaviour on a null argument depends on the conversion.

I intend to explain the function call and the error in your code.

Check Andy's link for details on formatting.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值