Java Decimal Round roundDouble(double numero, int ceros_a_la_derecha)

Here you can find the source of roundDouble(double numero, int ceros_a_la_derecha)

Description

round Double

License

Open Source License

Declaration

public static String roundDouble(double numero, int ceros_a_la_derecha) 

Method Source Code

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

import java.text.DecimalFormat;
import java.text.NumberFormat;

public class Main {
    public static String roundDouble(double numero, int ceros_a_la_derecha) {
        String mascara = "#.";
        String formateado = "";
        String num = "";

        for (int i = 0; i < ceros_a_la_derecha; i++) {
            mascara += "0";
        }//www. j a va  2  s . c o m
        NumberFormat formatter = new DecimalFormat(mascara);
        num = "" + formatter.format(numero);

        if (num.substring(0, 1).equals(".")) {
            formateado = "0" + num;
        } else {
            formateado = "" + num;
        }

        if (ceros_a_la_derecha == 0) {
            formateado = formateado.substring(0, formateado.length() - 1);
        }

        return formateado;
    }

    public static String roundDouble(String valor, int ceros_a_la_derecha) {
        double numero = Double.parseDouble(valor);
        String mascara = "#.";
        String formateado = "";
        String num = "";

        for (int i = 0; i < ceros_a_la_derecha; i++) {
            mascara += "0";
        }
        NumberFormat formatter = new DecimalFormat(mascara);
        num = "" + formatter.format(numero);

        if (num.substring(0, 1).equals(".")) {
            formateado = "0" + num;
        } else {
            formateado = "" + num;
        }

        if (ceros_a_la_derecha == 0) {
            formateado = formateado.substring(0, formateado.length() - 1);
        }

        return formateado;
    }
}

Related

  1. roundDecimalPlaces(final double input, final int decimalPlaces)
  2. roundDecimals(double d, int numOfDec)
  3. roundDistanceFromMeterToKm(final double distanceInMeter)
  4. roundDouble(double iVal)
  5. roundDouble(double num, int decimal)
  6. roundDouble(Double val, int precision)
  7. roundedNumber(double inVal)
  8. RoundFractionalTons(double d)
  9. roundNumDecimals(double d, int num)