Here you can find the source of addLeadingZeros(Object number, int places)
Parameter | Description |
---|---|
number | object representing a number. |
places | to the left of decimal to fill with zeros. |
Parameter | Description |
---|---|
NCSAException | if number is not a valid number. |
public static String addLeadingZeros(Object number, int places) throws IllegalArgumentException
//package com.java2s; public class Main { /**//from ww w . j a v a2s.co m * @param number * object representing a number. * @param places * to the left of decimal to fill with zeros. * @return String representation of number with leading zeros added. * @throws NCSAException * if number is not a valid number. */ public static String addLeadingZeros(Object number, int places) throws IllegalArgumentException { if (number == null) return null; if (number instanceof String) try { Double.valueOf((String) number); } catch (Throwable t) { throw new IllegalArgumentException( "addLeadingZeros, problem with string value " + number + ": " + t.getCause()); } else if (!(number instanceof Number)) throw new IllegalArgumentException(number + " is not a Number"); StringBuffer suffix = new StringBuffer(0); long l = 0; int start = 0; int end = -1; int zeros = places; suffix.append(number); if (suffix.toString().equals("null")) throw new IllegalArgumentException("no number string to modify"); if (suffix.charAt(0) == '-') start = 1; else start = 0; while (start < suffix.length() && suffix.charAt(start) == '0') suffix.deleteCharAt(start); end = suffix.indexOf("."); if (end < 0) end = suffix.length(); String intPart = suffix.substring(start, end); if (intPart == null || intPart.length() < 1) { l = 0; if (zeros > 0 || end == suffix.length()) suffix.insert(start, "0"); } else l = new Long(suffix.substring(start, end)).longValue(); do { zeros--; l /= 10; } while (l > 0); for (int i = 0; i < zeros; i++) suffix.insert(start, "0"); return suffix.toString(); } }