Java Float Number Format formatFloat(double number, int precision)

Here you can find the source of formatFloat(double number, int precision)

Description

Returns the specified double, formatted as a string, to n decimal places, as specified by precision.

License

Open Source License

Declaration

public static String formatFloat(double number, int precision) 

Method Source Code

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

public class Main {
    public static final int PRECISION = 1;

    /**//from  w  w w .  j a v  a  2 s.c  om
     * Returns the specified double, formatted as a string, to n decimal places,
     * as specified by precision.
     * <p/>
     * ie: formatFloat(1.1666, 1) -> 1.2 ie: formatFloat(3.1666, 2) -> 3.17 ie:
     * formatFloat(3.1666, 3) -> 3.167
     */
    public static String formatFloat(double number, int precision) {

        String text = Double.toString(number);
        if (precision >= text.length()) {
            return text;
        }

        int start = text.indexOf(".") + 1;
        if (start == 0)
            return text;
        if (precision == 0)
            return text.substring(0, start - 1);
        if (start <= 0)
            return text;
        else if ((start + precision) <= text.length())
            return text.substring(0, (start + precision));
        else
            return text;
    }

    public static String formatFloat(String text, int precision) {
        int start = text.indexOf(".") + 1;
        if (start == 0)
            return text;
        if (precision == 0)
            return text.substring(0, start - 1);
        if (start <= 0) {
            return text;
        } else if ((start + precision) <= text.length()) {
            return text.substring(0, (start + precision));
        } else
            return text;
    }

    /**
     * Returns the specified double, formatted as a string, to n decimal places,
     * as specified by precision.
     * <p/>
     * ie: formatFloat(1.1666, 1) -> 1.2 ie: formatFloat(3.1666, 2) -> 3.17 ie:
     * formatFloat(3.1666, 3) -> 3.167
     */
    public static String formatFloat(double number) {

        String text = Double.toString(number);
        if (PRECISION >= text.length()) {
            return text;
        }
        int start = text.indexOf(".") + 1;
        if (start == 0)
            return text;
        if (start <= 0) {
            return text;
        } else if ((start + PRECISION) <= text.length()) {
            return text.substring(0, (start + PRECISION));
        } else
            return text;
    }
}

Related

  1. formatFloat(double num)
  2. formatFloat(double value, int decimals)
  3. formatFloat(float f)
  4. formatFloat(float input, int numDecimals)
  5. formatFloat(float num, int width, int precision)