[java] Java: How to set Precision for double value?

I was working with numbers recently and I had a situation where I want to set the precision of a double value say to 6 digits or 4 digits, depending on the value stored in the database.

For example, If in the database the precision is set as 4 digits then the output must look as,

10.0000.

I tried with DecimalFormat and using the string ##.####, but it is annoying to use symbols everytime.

Is there any better approach, say something like below:

Double value = 10.0;
value.setPrecision(4);

This question is related to java

The answer is


BigDecimal value = new BigDecimal(10.0000);
value.setScale(4);

public static String setPrecision(String number, int decimal) {
    double nbr = Double.valueOf(number);
    int integer_Part = (int) nbr;
    double float_Part = nbr - integer_Part;
    int floating_point = (int) (Math.pow(10, decimal) * float_Part);
    String final_nbr = String.valueOf(integer_Part) + "." + String.valueOf(floating_point);
    return final_nbr;
}

This is an easy way to do it:

String formato = String.format("%.2f");

It sets the precision to 2 digits.

If you only want to print, use it this way:

System.out.printf("%.2f",123.234);

The precision of double and float is fixed by their size and the way the IEEE floating point types are implemented.

The number of decimal digits in the output, on the other hand, is a matter of formatting. You are correct that typing the same constant over and over is a bad idea. You should declare a string constant instead, and use its symbolic representation.

private static final String DBL_FMT = "##.####";

Using a symbolic representation would let you change precision in all places the constant is used without searching through your code.


Here's an efficient way of achieving the result with two caveats.

  1. Limits precision to 'maximum' N digits (not fixed to N digits).
  2. Rounds down the number (not round to nearest).

See sample test cases here.

123.12345678 ==> 123.123
1.230000 ==> 1.23
1.1 ==> 1.1
1 ==> 1.0
0.000 ==> 0.0
0.00 ==> 0.0
0.4 ==> 0.4
0 ==> 0.0
1.4999 ==> 1.499
1.4995 ==> 1.499
1.4994 ==> 1.499

Here's the code. The two caveats I mentioned above can be addressed pretty easily, however, speed mattered more to me than accuracy, so i left it here. String manipulations like System.out.printf("%.2f",123.234); are computationally costly compared to mathematical operations. In my tests, the below code (without the sysout) took 1/30th the time compared to String manipulations.

public double limitPrecision(String dblAsString, int maxDigitsAfterDecimal) {
    int multiplier = (int) Math.pow(10, maxDigitsAfterDecimal);
    double truncated = (double) ((long) ((Double.parseDouble(dblAsString)) * multiplier)) / multiplier;
    System.out.println(dblAsString + " ==> " + truncated);
    return truncated;
}

Maybe this method would help you for precising double values.

double truncate(double number)
    {
        int integerPart = (int) number;
        double fractionalPart = number - integerPart;
        fractionalPart *= 100;  //It is for upto two decimal values after point.
                                //You can increase the zeros to fulfill your needs.
        int fractPart = (int) fractionalPart;
        fractionalPart = (double) (integerPart) + (double) (fractPart)/100;
        return fractionalPart;
    }

This method will allow to set the precision level.

double truncate(double number, int precision)
{
    double prec = Math.pow(10, precision);
    int integerPart = (int) number;
    double fractionalPart = number - integerPart;
    fractionalPart *= prec;
    int fractPart = (int) fractionalPart;
    fractionalPart = (double) (integerPart) + (double) (fractPart)/prec;
    return fractionalPart;
}

To set precision for double values DecimalFormat is good technique. To use this class import java.text.DecimalFormat and create object of it for example

double no=12.786;
DecimalFormat dec = new DecimalFormat("#0.00");
System.out.println(dec.format(no));

So it will print two digits after decimal point here it will print 12.79


To expand on @EJP, the concept of 'precision' when dealing with doubles is extremely fraught. As discussed in https://stackoverflow.com/a/3730040/390153 you can't even represent 0.1 as a double regardless of the precision, for the same reason you can't represent 1/3 in base 10 with finite precision.

You need to consider the problem you are trying to solve, and consider:

a) Should I be using doubles in the first place; if precision is a relevant concept, then using doubles may well be a mistake.

b) If doubles are appropriate, what do I mean by precision? If you are only talking about display, wrap the logic in a display function and you will only need to deal with it in one place; ie. apply the DRY principle.


You can try BigDecimal for this purpose

Double toBeTruncated = new Double("3.5789055");

Double truncatedDouble = BigDecimal.valueOf(toBeTruncated)
    .setScale(3, RoundingMode.HALF_UP)
    .doubleValue();

This worked for me:

public static void main(String[] s) {
        Double d = Math.PI;
        d = Double.parseDouble(String.format("%.3f", d));  // can be required precision
        System.out.println(d);
    }