Java String.format()带半偶数舍入
我想使用String.format()将一些大小数格式化为字符串的一部分:Java String.format()带半偶数舍入,java,string-formatting,formatter,Java,String Formatting,Formatter,我想使用String.format()将一些大小数格式化为字符串的一部分: // Example: String getPrice( String pattern ) { BigDecimal price = basePrice.multiply( BigDecimal.ONE.add( vatRate ) ); BigDecimal priceInPence = price.multiply( new BigDecimal( "100" ) ); BigDecimal annual
// 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"
但是for String.format()表示,任何大小数的舍入都将使用半向上舍入,而我甚至需要半向上舍入
我知道如何手动设置BigDecimals()的比例,但在本例中,我希望能够使用任意模式字符串(包括非数字模式元素),因此我不知道要使用什么比例
因此,我的问题是:
- 我可以设置String.format()使用的舍入模式吗?或
- 是否有另一个格式化程序或库可以像我的示例中那样格式化数字
BigDecimal\toString()
我可以设置string.format()使用的舍入模式吗简短回答:没有 是否有其他格式化程序或库可以像我的示例中那样格式化数字?
BigDecimal通过
new MathContext(compPrec)
或普通HALF\u UP
进行内部转换。
您可以使用最新(或您喜欢的)java版本的java.util.Formatter
代码,修改MathContext的创建以使用HALF_偶数。工作时间应为10-15分钟。但是您需要一个自定义方法来模拟String.format
:
public static String format(String format, Object... args) {
return new FormatterHALF_EVEN().format(format, args).toString();
}
真正“可靠”的建议是在项目中添加5000行自重代码!据我所见,格式化程序不会设置缩放,除非它已经设置为所需的缩放。因此,请帮助解决此问题,解析格式字符串并设置您的比例:
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);
}
通过这些数字,我得到以下输出:
你们的价格是3450.000便士/天(12592.50英镑/年),包括增值税
每年约12592英镑
因此它应用了正确的舍入。看看java.math.MathContext。您可以使用java.math.RoundingMode(半偶数)构造MathContext,然后将其传递给BigDecimal的构造函数或其中一个乘法方法:
multiply(BigDecimal multipliand,MathContext mc)
@mttdbrd-对不起,我应该说明我需要基于该模式的任意精度(请参见上面的编辑)。和@ComputerFellow-抱歉,这些是关于大小数的答案,我的问题是关于更改String.Format()使用的舍入模式的问题是,直到运行时我才知道使用什么比例:精度信息在模式字符串中。我喜欢这种方法。如果将它扩展一点,以处理一个代币在不同规模下被多次使用的情况,可能会更好:getPrice(“每年大约%2$.0f(确切地说是%2.2f)”;