BeanIO DoubleTypeHandler模​​式

时间:2018-01-31 00:30:50

标签: java bean-io

我正在使用这种模式:

<typeHandler name="dblHandler" class="org.beanio.types.DoubleTypeHandler">
        <property name="pattern" value="##0.0000000000;-#0.0000000000"/>
</typeHandler> 

这会将数字转换为10个小数点。但是,如果数字有7个小数点,则会增加3个尾随0&#39; s。如何将模式更改为不添加尾随0

示例:

  • 如果number为8.7829214389,则转换为8.7829214389。
  • 如果number为8.7829214,则转换应为8.7829214。它正在转换 它来:8.7829214 000
  • 如果number为8.7829,则转换应为8.7829。它正在转换它 至:8.7829 000000

谢谢!

1 个答案:

答案 0 :(得分:2)

我很快写了这个来测试DecimalFormat

final DecimalFormat format = (DecimalFormat) NumberFormat.getInstance();
String pattern = "##0.0000000000;-#0.0000000000";
format.applyPattern(pattern);

System.out.println("Using pattern: " + pattern);
System.out.println("8.7829214389 = " + format.format(-8.7829214389));
System.out.println("8.7829214 = " + format.format(-8.7829214));
System.out.println("8.7829 = " + format.format(-8.7829));
System.out.println("8.123456789012 = " + format.format(-8.123456789012));
System.out.printf("%n");
System.out.println("-8.7829214389 = " + format.format(-8.7829214389));
System.out.println("-8.7829214 = " + format.format(-8.7829214));
System.out.println("-8.7829 = " + format.format(-8.7829));
System.out.println("-8.123456789012 = " + format.format(-8.123456789012));
System.out.printf("==========%n%n");

final DecimalFormat format2 = (DecimalFormat) NumberFormat.getInstance();
pattern = "##0.##########;-#0.##########";
format2.applyPattern(pattern);
System.out.println("Using pattern: " + pattern);
System.out.println("8.7829214389 = " + format2.format(8.7829214389));
System.out.println("8.7829214 = " + format2.format(8.7829214));
System.out.println("8.7829 = " + format2.format(8.7829));
System.out.println("8.123456789012 = " + format2.format(8.123456789012));
System.out.printf("%n");
System.out.println("-8.7829214389 = " + format2.format(-8.7829214389));
System.out.println("-8.7829214 = " + format2.format(-8.7829214));
System.out.println("-8.7829 = " + format2.format(-8.7829));
System.out.println("-8.123456789012 = " + format2.format(-8.123456789012));
System.out.printf("==========%n%n");

制作此输出:

Using pattern: ##0.0000000000;-#0.0000000000
8.7829214389 = -8.7829214389
8.7829214 = -8.7829214000
8.7829 = -8.7829000000
8.123456789012 = -8.1234567890

-8.7829214389 = -8.7829214389
-8.7829214 = -8.7829214000
-8.7829 = -8.7829000000
-8.123456789012 = -8.1234567890
==========

Using pattern: ##0.##########;-#0.##########
8.7829214389 = 8.7829214389
8.7829214 = 8.7829214
8.7829 = 8.7829
8.123456789012 = 8.123456789

-8.7829214389 = -8.7829214389
-8.7829214 = -8.7829214
-8.7829 = -8.7829
-8.123456789012 = -8.123456789
==========

模式中小数点后10位零数字强制格式化程序始终在小数点后打印10位数。如果您只想打印不超过10位,请使用#表示小数点后的所有数字都是可选的。有关详细信息,请参阅the Java API documentation for DecimalFormat

因此,将类型处理程序的模式更改为:

<typeHandler name="dblHandler" class="org.beanio.types.DoubleTypeHandler">
        <property name="pattern" value="##0.##########;-#0.##########"/>
</typeHandler>