Java String.format() 与 HALF_EVEN 四舍五入 [英] Java String.format() with HALF_EVEN rounding
问题描述
我想使用 String.format() 将一些 BigDecimals 格式化为字符串的一部分:
I'd like to use String.format() to format some BigDecimals as part of a string:
// Example:
String getPrice( String pattern )
{
BigDecimal price = basePrice.multiply( BigDecimal.ONE.add( vatRate ) );
BigDecimal priceInPence = price.multiply( new BigDecimal( "100" ) );
BigDecimal annualPrice = price.multiply( new BigDecimal( "365" ) );
return String.format( pattern, priceInPence, annualPrice );
}
String myPrice1 = getPrice( "Your price is %1$.3fp/day (£2$.2f/year) including VAT" );
// --> "Your price is 32.100p/day (£117.16/year) including VAT"
String myPrice2 = getPrice( "Around £%2$.0f annualy" );
// --> "Around £117 annually"
但是文档对于 String.format() 来说,BigDecimals 的任何舍入都将使用 HALF_UP 舍入来完成,而我需要 HALF_EVEN.
However the docs for String.format() say that any rounding of BigDecimals will be done with HALF_UP rounding, whereas I need HALF_EVEN.
我知道如何手动设置 BigDecimals 的比例(设置 BigDecimal 的特定精度) - 但在这种情况下,我希望能够使用任意模式字符串(包括非数字模式元素),所以我不会提前知道要使用什么比例.
I know how to manually set the scale of BigDecimals (Set specific precision of a BigDecimal) - but in this case I want to be able to use an arbitrary pattern string (including non-numeric pattern elements), so I won't know in advance what scale to use.
因此我的问题是:
我可以设置 String.format() 使用的舍入模式吗?或
是否有另一个格式化程序或库可以像我的示例那样格式化数字?
is there another formatter or library that would format the numbers as in my example?
推荐答案
真的很扎实"建议将 5000 行无意义代码添加到您的项目中!从我看来,格式化程序不会设置比例,除非它已经设置为需要的值.所以帮帮忙,解析格式字符串并设置您的比例:
Really "solid" advice to add 5000 lines of dead-weight code to your project! From what I see, the Formatter will not set scale unless it is already set to what is needed. So help it out, parse the format string and set your scale:
public static String getPrice(String pattern) {
BigDecimal basePrice = new BigDecimal("23");
BigDecimal vatRate = new BigDecimal("0.5");
BigDecimal price = basePrice.multiply(BigDecimal.ONE.add(vatRate));
BigDecimal priceInPence = price.multiply(new BigDecimal("100"));
BigDecimal annualPrice = price.multiply(new BigDecimal("365"));
Matcher matcher = Pattern.compile("%(\\d+)\\$.(\\d+)f").matcher(pattern);
while (matcher.find()) {
String index = matcher.group(1);
int scale = Integer.parseInt(matcher.group(2));
if (index.equals("1"))
priceInPence = priceInPence.setScale(scale, RoundingMode.HALF_EVEN);
else if (index.equals("2"))
annualPrice = annualPrice.setScale(scale, RoundingMode.HALF_EVEN);
}
return String.format(pattern, priceInPence, annualPrice);
}
有了这些数字,我得到了这个输出:
with these numbers I get this output:
您的价格为 3450.000p/天(12592.50 英镑/年),包括增值税
Your price is 3450.000p/day (£12592.50/year) including VAT
每年约 12592 英镑
Around £12592 annualy
所以它应用了正确的舍入.
So it applies correct rounding.
这篇关于Java String.format() 与 HALF_EVEN 四舍五入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!