Java Double Number Format format(double val, int n, int w)

Here you can find the source of format(double val, int n, int w)

Description

format

License

Open Source License

Declaration

public static String format(double val, int n, int w) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2012 Jakub Kov???, Katar?na Kotrlov?, Pavol Luk??a, Viktor Tomkovi??, Tatiana T?thov?
 *
 * This program 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 3 of the License, or
 * (at your option) any later version./*from w  ww  .  j a  va  2s  .c  om*/
 *
 * 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.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 ******************************************************************************/

public class Main {
    private static final String ZEROES = "000000000000";
    private static final String BLANKS = "            ";

    public static String format(double val, int n, int w) { // rounding
        double incr = 0.5;
        for (int j = n; j > 0; j--) {
            incr /= 10;
        }
        val += incr;
        String s = Double.toString(val);
        final int n1 = s.indexOf('.');
        final int n2 = s.length() - n1 - 1;
        if (n > n2) {
            s = s + ZEROES.substring(0, n - n2);
        } else if (n2 > n) {
            s = s.substring(0, n1 + n + 1);
        }
        if (w > 0 && w > s.length()) {
            s = BLANKS.substring(0, w - s.length()) + s;
        } else if (w < 0 && (-w) > s.length()) {
            w = -w;
            s = s + BLANKS.substring(0, w - s.length());
        }
        return s;
    }
}

Related

  1. format(double number)
  2. format(Double number)
  3. format(double number, int nums)
  4. format(double number, int precision)
  5. format(double size, String type)
  6. format(double value, int decimalPlaces)
  7. format(double value, int digits)
  8. format(final double power)
  9. formatDouble(double d)