Java Fraction Format format(double d, DecimalFormat unitFormatter)

Here you can find the source of format(double d, DecimalFormat unitFormatter)

Description

format

License

Open Source License

Declaration

protected static String format(double d, DecimalFormat unitFormatter) 

Method Source Code


//package com.java2s;
/*-/* ww  w . j av  a 2  s .  c  o m*/
 * Copyright (C) 2006-2008 Erik Larsson
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.text.DecimalFormat;

public class Main {
    protected static String format(double d, DecimalFormat unitFormatter) {
        final double rounded = roundDoubleToDecimals(d, unitFormatter.getMaximumFractionDigits());
        return unitFormatter.format(rounded);
    }

    public static double roundDoubleToDecimals(double d, int decimals) {
        long integerPart = (long) d;
        double remaining = d - integerPart;
        if (decimals > 0) {
            BigDecimal bd = new BigDecimal(remaining, new MathContext(decimals, RoundingMode.DOWN));
            return integerPart + bd.doubleValue();
        } else
            return (double) integerPart;
    }
}

Related

  1. format(double d)
  2. format(double d)
  3. format(Double d, int digit)
  4. format(double d, java.text.NumberFormat format)
  5. format(double degrees)
  6. format(double input, String format)