Java Fraction Format format(final double value, final int decimalPlaces)

Here you can find the source of format(final double value, final int decimalPlaces)

Description

Formats a double value with a given number of decimal places.

License

Open Source License

Parameter

Parameter Description
value The value to format.
decimalPlaces The desired number of decimal places.

Return

The formatted string.

Declaration

public static String format(final double value, 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 {
    /**// w  w w  .j av  a2  s . c o m
     * Formats a double value with a given number of decimal places.
     *
     * @param value The value to format.
     * @param decimalPlaces The desired number of decimal places.
     * @return The formatted string.
     */
    public static String format(final double value, final int decimalPlaces) {
        final DecimalFormat formatter = getDecimalFormat(decimalPlaces);
        return formatter.format(value);
    }

    /**
     * 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. format(double value, String formatString)
  2. format(double x, int max, int min)
  3. format(final double d)
  4. format(final double number)
  5. format(final double value)
  6. format(final NumberFormat fmt, final double val)
  7. format(float f)
  8. format(Float f)
  9. format(float num)