【发布时间】:2014-11-09 23:10:48
【问题描述】:
我想使用 String.format() 将一些 BigDecimal 格式化为字符串的一部分:
// 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() 的 docs 表示 BigDecimals 的任何舍入都将使用 HALF_UP 舍入完成,而我需要 HALF_EVEN。
我知道如何手动设置 BigDecimals 的比例 (Set specific precision of a BigDecimal) - 但在这种情况下,我希望能够使用任意模式字符串(包括非数字模式元素),所以我不知道提前使用什么比例。
因此我的问题是:
我可以设置 String.format() 使用的舍入模式吗?或者
是否有其他格式化程序或库可以像我的示例那样格式化数字?
【问题讨论】:
-
看看 java.math.MathContext。您可以使用 java.math.RoundingMode (HALF_EVEN) 构造 MathContext,然后将其传递给 BigDecimal 的构造函数或乘法方法之一:
multiply(BigDecimal multiplicand, MathContext mc) -
@mttdbrd - 抱歉,我应该根据模式明确我需要任意精度(参见我上面的编辑)。
-
@ComputerFellow - 抱歉,这些是关于 BigDecimals 的答案,我的问题是关于更改 String.Format() 使用的舍入模式
标签: java string-formatting formatter