Java Utililty Methods Number Format

List of utility methods to do Number Format

Description

The list of methods to do Number Format are organized into topic(s).

Method

StringformatNumberWithExtension(int num)
format Number With Extension
int n = num;
while (n > 10)
    n = n % 10;
String append = "";
if (n == 1)
    append = (num == 11 ? "th" : "st");
else if (n == 2)
    append = (num == 12 ? "th" : "nd");
...
StringformatNumberWithKSeparators(int value)
Formats the number in value with thousand separator "," for display.
StringBuilder sb = new StringBuilder(16);
String number = String.valueOf(value);
int len = number.length();
int end = len % 3, i = 0;
sb.append(number.substring(0, end));
for (i = end; i <= (len - 3); i += 3) {
    if (i > 0) {
        sb.append(",");
...
StringformatNumberWithSameWidth(int d)
format Number With Same Width
return formatNumberWithSameWidth(d, String.valueOf(d).length());
StringformatOnlyLettersNumbersAndSpaces(String keyword)
format Only Letters Numbers And Spaces
StringBuilder result = new StringBuilder();
if (!isEmpty(keyword)) {
    for (int i = 0; i < keyword.length(); i++) {
        char ch = keyword.charAt(i);
        if (Character.isLetterOrDigit(ch) || Character.isWhitespace(ch)) {
            result.append(ch);
return result.toString();
StringformatPaddedNumber(long number, int numericPadding)
format Padded Number
StringBuilder outStrBfr = new StringBuilder(Long.toString(number));
while (numericPadding > outStrBfr.length()) {
    outStrBfr.insert(0, '0');
return outStrBfr.toString();
StringformatPartialName(String name, int numberOfCharacters)
Displays the end of the name if the name is longer that the number of specified characters.
if (name == null)
    return null;
int n = DOTS.length() + numberOfCharacters;
int m = name.length();
if (m <= n)
    return name;
StringBuffer buffer = new StringBuffer();
buffer.append(DOTS);
...
StringformatPattern(String number, String pattern)
format Pattern
StringBuffer str = new StringBuffer();
number = removeInvalidChars(number);
for (int i = 0, j = 0; i < number.length(); j++) {
    if (j < pattern.length()) {
        char c = pattern.charAt(j);
        if (c == 'x' || c == 'X')
            str.append(number.charAt(i++));
        else
...
StringformatPct(final Number amount)
Format the given amount into human readable string.
if (amount == null) {
    return "--";
} else {
    return amount.doubleValue() + "%";
StringformatPercentage(Number numerator, Number denominator)
format Percentage
return String.format("%.2f%%", 100.0 * numerator.doubleValue() / denominator.doubleValue());
StringformatPhone(String phoneNumber, String formattingPattern, String countryCode)
Format phone numbers (to international phone number format - eg +41 41 882 32 21)
if (phoneNumber == null) {
    return null;
if (formattingPattern == null) {
    return phoneNumber;
if (countryCode == null) {
    return phoneNumber;
...