Java Decimal Format getDecimalFormat(final int decimalPlaces)

Here you can find the source of getDecimalFormat(final int decimalPlaces)

Description

Gets a decimal format that with the desired number of decimal places.

License

Open Source License

Parameter

Parameter Description
decimalPlaces The number of decimal places.

Return

The desired decimal format.

Declaration

public static DecimalFormat getDecimalFormat(final int decimalPlaces) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.text.*;
import java.util.Arrays;

public class Main {
    /**//from ww w. j av a2  s.c  o  m
     * Gets a decimal format that with the desired number of decimal places.
     *
     * @param decimalPlaces The number of decimal places.
     * @return The desired decimal format.
     */
    public static DecimalFormat getDecimalFormat(final int decimalPlaces) {
        if (decimalPlaces < 0) {
            throw new IllegalArgumentException("decimalPlaces must be non-negative");
        }

        final DecimalFormatSymbols decimalFormatSymbols = new DecimalFormatSymbols();
        decimalFormatSymbols.setDecimalSeparator('.');
        final StringBuilder builder = new StringBuilder();
        builder.append("#0");

        if (decimalPlaces > 0) {
            builder.append('.');
            final char[] zeros = new char[decimalPlaces];
            Arrays.fill(zeros, '0');
            builder.append(zeros);
        }

        final DecimalFormat format = new DecimalFormat(builder.toString(), decimalFormatSymbols);
        format.setGroupingUsed(false);
        return format;
    }
}

Related

  1. getCorrectionValue(double basicValue, int digit)
  2. getDecimalFormat()
  3. getDecimalFormat()
  4. getDecimalFormat()
  5. getDecimalFormat()
  6. getDecimalFormat(int decimalPlaces, Locale locale)
  7. getDecimalFormat(int precision)
  8. getDecimalFormat(int precision)
  9. getDecimalFormat(int precision, String force)