[英]BeanIO: Format number with fixed length for integer and decimal places without separator
有沒有辦法使用Anotation格式化固定長度添加分隔符的數字? 我總是收到 10 個 integer 位置和 2 個十進制,得到 12 的固定長度
我使用的字段注釋:
@Field(at=576, length=12, format="###.##")
private BigDecimal impTotal;
有一個例子:
Received: 00000000000150
Value expected: 1.50
我用它來解決它,但我認為它可能會減慢進程:
public BigDecimal getImpTotal() {
return impTotal.divide(new BigDecimal(100));
}
正如您所注意到的,您提供的模式不會將字符串強制轉換為您所期望的。 您可以按照您當前的方式進行操作,但是當您必須進行反向操作並且 output 是固定長度格式的值時,您必須乘以 100 才能獲得所需的 output。
最好使用TypeHandler實現來為您完成所有這些工作。 我無法評論您的實現與類型處理程序的性能,您需要對其進行基准測試。
您需要實現org.beanio.types.TypeHandler
接口。 有關進一步的解釋,請參閱 JavaDoc 注釋
import org.beanio.types.TypeHandler;
public class MyImpTotalTypeHandler implements TypeHandler {
private static final BigDecimal BIG_DECIMAL_100_2 = new BigDecimal(100).setScale(2, RoundingMode.HALF_UP);
private static final BigDecimal BIG_DECIMAL_100 = new BigDecimal(100).setScale(0, RoundingMode.HALF_UP);
/**
* We are essentially receiving a (Big)Integer that must be converted to a BigDecimal.
*
* @see org.beanio.types.TypeHandler#parse(java.lang.String)
*/
@Override
public Object parse(final String value) throws TypeConversionException {
System.out.printf("Parsing value: %s%n", value);
return new BigDecimal(value).divide(BIG_DECIMAL_100_2);
}
/**
* To output the value from which this BigDecimal was created, we need to multiply the value with 100.
*
* {@inheritDoc}
*
* @see org.beanio.types.TypeHandler#format(java.lang.Object)
*/
@Override
public String format(final Object value) {
System.out.printf("Formatting value: %s%n", value);
return value != null ? ((BigDecimal) value).multiply(BIG_DECIMAL_100).toPlainString() : "";
}
@Override
public Class<?> getType() {
return BigDecimal.class;
}
}
然后,您必須使用StreamBuilder
注冊您的類型處理程序
final StreamBuilder builder = new StreamBuilder(this.getClass().getSimpleName())
// your set up here
// add a TypeHandler to handle the implTotal
.addTypeHandler("MyImpTotalTypeHandler", BigDecimal.class, new MyImpTotalTypeHandler())
然后在您希望使用它的字段上引用此類型處理程序:
@Field(at = 576, length = 12, handlerName = "MyImpTotalTypeHandler")
private BigDecimal impTotal;
您還可以查看擴展現有的org.beanio.types.BigDecimalTypeHandler
,但它可能不像您自己的實現那么簡單。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.