Java Number Format formatNumber(String s, Character thousandsSeparator, Character decimalSeparator)

Here you can find the source of formatNumber(String s, Character thousandsSeparator, Character decimalSeparator)

Description

in order to transform the number "1234567.89" to string 123,456.89

License

Open Source License

Declaration

public static String formatNumber(String s, Character thousandsSeparator, Character decimalSeparator) 

Method Source Code

//package com.java2s;
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt

public class Main {
    /**/*from  w  w w.  j ava 2s  . c o  m*/
     * in order to transform the number "1234567.89" to string 123,456.89
     */
    public static String formatNumber(String s, Character thousandsSeparator, Character decimalSeparator) {
        if (s == null) {
            return null;
        }
        String result = s;
        int decimalIndex = s.indexOf("."); //$NON-NLS-1$

        if (decimalIndex == -1) {
            if (thousandsSeparator != null) {
                return formatNumber(result, thousandsSeparator);
            } else {
                return result;
            }
        }

        if (thousandsSeparator != null) {
            result = formatNumber(s.substring(0, decimalIndex), thousandsSeparator);
        } else {
            result = s.substring(0, decimalIndex);
        }

        if (decimalSeparator != null) {
            result += (s.substring(decimalIndex)).replace('.', decimalSeparator);
        } else {
            result += s.substring(decimalIndex);
        }
        return result;
    }

    private static String formatNumber(String s, char thousandsSeparator) {

        StringBuilder sb = new StringBuilder(s);
        int index = sb.length();

        index = index - 3;
        while (index > 0 && sb.charAt(index - 1) != '-') {
            sb.insert(index, thousandsSeparator);
            index = index - 3;
        }

        return sb.toString();
    }
}

Related

  1. formatNumber(long value)
  2. formatNumber(Number number)
  3. formatNumber(Object num)
  4. formatNumber(String formatStr, int length, boolean leftPadding, char paddingCharacter)
  5. formatNumber(String num, int n)
  6. formatNumber(String value)
  7. formatNumberFloorWithPostfix(int value)
  8. formatNumberImpl(long i, int digits, String fill)
  9. formatNumbers(final int... numbers)