Here you can find the source of format(final long number, final int length)
Parameter | Description |
---|---|
number | Format this long. |
length | Maximum length. Must not be bigger than 20 and less than 1. |
length
, trimmed with leading spaces.
public static final String format(final long number, final int length)
//package com.java2s; /* This file is part of the project "Hilbert II" - http://www.qedeq.org * * Copyright 2000-2013, Michael Meyling <mime@qedeq.org>. * * "Hilbert II" is free software; you can redistribute * it and/or modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. *///from w w w . j a v a 2 s.c o m public class Main { /** For trimming with zeros. */ static final String FORMATED_ZERO = "00000000000000000000"; /** * Trim an integer with leading zeros to a given maximum length. * * @param number Format this long. * @param length Maximum length. Must not be bigger than 20 and less than 1. * @return String with minimum <code>length</code>, trimmed with leading spaces. */ public static final String format(final long number, final int length) { if (length > FORMATED_ZERO.length()) { throw new IllegalArgumentException("maximum length " + FORMATED_ZERO + " exceeded: " + length); } if (length < 1) { throw new IllegalArgumentException("length must be bigger than 0: " + length); } final String temp = FORMATED_ZERO + number; return temp.substring(Math.min(temp.length() - length, FORMATED_ZERO.length())); } /** * Return substring of text. Position might be negative if length is big enough. If the string * limits are exceeded this method returns at least all characters within the boundaries. * If no characters are within the given limits an empty string is returned. * * @param text Text to work on. Must not be <code>null</code>. * @param position Starting position. Might be negative. * @param length Maximum length to get. * @return Substring of maximum length <code>length</code> and starting with position. * @throws NullPointerException <code>text</code> is <code>null</code>. */ public static String substring(final String text, final int position, final int length) { final int start = Math.max(0, position); int l = position + length - start; if (l <= 0) { return ""; } int end = start + l; if (end < text.length()) { return text.substring(start, end); } return text.substring(start); } }