我正在编写一个应用程序,需要将不同长度和不同精度的小数输出为字符串,但不带小数点,以便将其写入平面文件并输入到另一个系统中。例如:
我编写的处理函数如下,将被调用数十万次,因此我想确保没有更好、更高效的方法来处理这个问题。我已经研究了许多方法,想让DecimalFormat为我做更多的事情,但我发现它无法满足我的需求,即在不使用小数点的情况下格式化小数位数。
12345 -> Length:10, Scale:2 -> 0001234500
123.45 -> Length:10, Scale:2 -> 0000012345
123.45 -> Length:10, Scale:3 -> 0000123450
-123.45 -> Length:10, Scale:3, signed:true -> -000123450
123.45 -> Length:10, Scale:3, signed:true -> +000123450
我编写的处理函数如下,将被调用数十万次,因此我想确保没有更好、更高效的方法来处理这个问题。我已经研究了许多方法,想让DecimalFormat为我做更多的事情,但我发现它无法满足我的需求,即在不使用小数点的情况下格式化小数位数。
protected String getFormattedDecimal( String value, int len, int scale, Boolean signed ) throws Exception{
StringBuffer retVal = new StringBuffer();
//Need a BigDecimal to facilitiate correct formatting
BigDecimal bd = new BigDecimal( value );
//set the scale to ensure that the correct number of zeroes
//at the end in case of rounding
bd = bd.setScale( scale );
//taking it that if its supposed to have negative it'll be part of the num
if ( ( bd.compareTo( BigDecimal.ZERO ) >= 0 ) && signed ){
retVal.append( "+" );
}
StringBuffer sbFormat = new StringBuffer();
for (int i = 0; i < len; i++)
{
sbFormat.append('0');
}
DecimalFormat df = new DecimalFormat( sbFormat.toString() );
retVal.append( df.format( bd.unscaledValue() ) );
return retVal.toString();
}