Java examples for java.lang:double Format
Zero pad the decimal part of the argument until it reach the specified scale and then zero pad the integer part until the whole resulting string reach the specified total Length.
import java.math.BigDecimal; import java.text.DecimalFormat; public class Main{ public static void main(String[] argv) throws Exception{ BigDecimal value = new BigDecimal("1234"); int totalLength = 2; int scale = 2; System.out.println(zeroPad(value,totalLength,scale)); }//from ww w . ja v a 2s.c o m /** * Zero pad the decimal part of the argument until it reach the * specified scale and then zero pad the integer part until the whole * resulting string reach the specified totalLength (also the decimal * separator is counted). * * @param value * a BigDecimal to be zero-padded * @param totalLength * the total length, including the decimal point and the * decimal digits * @param scale * number of digits after the decimal point * @return a zero-padded String representation * @throws IllegalArgumentException * when the BigDecimal is negative, since is not * supported */ public static String zeroPad(final BigDecimal value, final int totalLength, final int scale) throws IllegalArgumentException { if (BdHelper.compare(value, 0) < 0) { throw new IllegalArgumentException( "BigDecimal attribute can't be negative"); } String format, zero = "0"; int integerLength = totalLength - scale - 1; BigDecimal rounded = value.setScale(scale, BigDecimal.ROUND_HALF_EVEN); format = StringHelper.repeat(zero, integerLength) + "." + StringHelper.repeat(zero, scale); DecimalFormat df = new DecimalFormat(format); return df.format(rounded.doubleValue()); } /** * Compare the BigDecimal first to the int second. * * @param first * first number to compare * @param second * second number to compare * @return a negative value, 0, or a positive value as this BigDecimal * is numerically less than, equal to, or greater than val. */ public static int compare(final BigDecimal first, final int second) { return first.compareTo(new BigDecimal(second)); } }