Java BigDecimal Format formatDecimal(BigDecimal number, int maxFractionDigits, int minFractionDigits)

Here you can find the source of formatDecimal(BigDecimal number, int maxFractionDigits, int minFractionDigits)

Description

Formats a number so that the number of digits in the fraction portion of it is bound by a maximum value and a minimum value.

License

Apache License

Parameter

Parameter Description
number a parameter
maxFractionDigits maximum number of fraction digits, replaced by 0 if it is a negative value
minFractionDigits minimum number of fraction digits, replaced by 0 if it is a negative value

Declaration

public static String formatDecimal(BigDecimal number, int maxFractionDigits, int minFractionDigits) 

Method Source Code

//package com.java2s;
/*// w  ww.j a  v a 2 s  . c  o  m
 *  Copyright 2014 AT&T
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
*/

import java.math.BigDecimal;

import java.text.DecimalFormat;

public class Main {
    /**
     * Formats a number so that the number of digits in the fraction
     * portion of it is bound by a maximum value and a minimum value.
     * <br>
     * <br>
     * Examples with maxFractionDigits being 3 and
     * minFractionDigits being 0:
     * <br>2.4535 -> 2.454
     * <br>20 -> 20
     * <br>24535 -> 24535
     * <br>2.5 -> 2.5
     * <br>2.460 -> 2.46
     * <br>2.40 -> 2.4
     * <br>3.12 -> 3.12
     * <br>9.888 -> 9.888
     *
     * @param number
     * @param maxFractionDigits maximum number of fraction digits,
     * replaced by 0 if it is a negative value
     * @param minFractionDigits minimum number of fraction digits,
     * replaced by 0 if it is a negative value
     * @return
     */
    public static String formatDecimal(BigDecimal number, int maxFractionDigits, int minFractionDigits) {
        DecimalFormat df = new DecimalFormat();
        df.setGroupingUsed(false);
        df.setMaximumFractionDigits(maxFractionDigits);
        df.setMinimumFractionDigits(minFractionDigits);
        return df.format(number);
    }
}

Related

  1. formatBigDecimalWithPrecise(BigDecimal number)
  2. formatCents(int cents)
  3. formatCUBRIDNumber(BigDecimal value)
  4. formatDecimal(BigDecimal b)
  5. formatDecimal(BigDecimal num)
  6. formatDecimalCost(BigDecimal value)
  7. formatDigit(double value, int scale)
  8. formatDouble(double d)
  9. formatDouble(Double someDouble, int digitsToTheRightOfDecimal)