Java Number Format formatNumber(final long number)

Here you can find the source of formatNumber(final long number)

Description

Formats the given number into one where thousands are separated by a space.

License

Open Source License

Parameter

Parameter Description
number The number to format

Return

Formatted string (e.g. "1 315 124" for 1315124)

Declaration

public static String formatNumber(final long number) 

Method Source Code

//package com.java2s;
/***********************************************************************************
 * /*from  w  w w.j  a  va2 s  .  c o  m*/
 * Copyright (c) 2014 Kamil Baczkowicz
 * 
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 * 
 *    Kamil Baczkowicz - initial API and implementation and/or initial documentation
 *    
 */

public class Main {
    /**
     * Formats the given number into one where thousands are separated by a space.
     * 
     * @param number The number to format
     * @return Formatted string (e.g. "1 315 124" for 1315124)
     */
    public static String formatNumber(final long number) {
        long divided = number;
        final StringBuffer sb = new StringBuffer();

        while (divided > 1000) {
            long rest = divided % 1000;
            sb.insert(0, " " + String.format("%03d", rest));

            divided = divided / 1000;
        }

        long rest = divided % 1000;
        sb.insert(0, rest);

        return sb.toString();
    }
}

Related

  1. formatNumber(double dscore)
  2. formatNumber(double number, int decimalPlaces)
  3. formatNumber(Double val, int numDec, int width)
  4. formatNumber(double value)
  5. formatNumber(double value)
  6. formatNumber(final String number)
  7. formatNumber(final StringBuilder buf, final long number)
  8. formatNumber(float num, int fragmentSize)
  9. formatNumber(int number)