I'm writing an app that needs to output Decimals of varying lengths, and varying scale to strings without the decimal point for writing to a flat file as input to another system. e.g.
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
The function I have written to handle this is below and is going to be called hundreds of thousands of times so I want to make sure that there's not a better, more efficient way to do this. I've looked at ways to get DecimalFormat to do more for me but I can't see it handling my need to format with decimal places but without decimal point.
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();
}