public static String toZeroPaddedString ( long value , int precision , int maxSize ) { StringBuffer sb = new StringBuffer ( ) ; if ( value < 0 ) { value = - value ; } String s = Long . toString ( value ) ; if ( s . length ( ) > precision ) { s = s . substring ( precision ) ; } for ( int i = s . length ( ) ; i < precision ; i ++ ) { sb . append ( ' ' ) ; } sb . append ( s ) ; if ( maxSize < precision ) { sb . setLength ( maxSize ) ; } return sb . toString ( ) ; }
If necessary adds zeros to the beginning of a value so that the total length matches the given precision otherwise trims the right digits . Then if maxSize is smaller than precision trims the right digits to maxSize . Negative values are treated as positive