Java: How to set Precision for double value?

Java

Java Problem Overview


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);

Java Solutions


Solution 1 - Java

You can try BigDecimal for this purpose

Double toBeTruncated = new Double("3.5789055");

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

Solution 2 - Java

You can't set the precision of a double (or Double) to a specified number of decimal digits, because floating-point values don't have decimal digits. They have binary digits.

You will have to convert into a decimal radix, either via BigDecimal or DecimalFormat, depending on what you want to do with the value later.

See also my answer to this question for a refutation of the inevitable *100/100 answers.

Solution 3 - Java

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);

Solution 4 - Java

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

Solution 5 - Java

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);
    }

Solution 6 - Java

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;
}

Solution 7 - Java

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.

Solution 8 - Java

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

Solution 9 - Java

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.

Solution 10 - Java

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;
}

Solution 11 - Java

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;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKiranView Question on Stackoverflow
Solution 1 - JavaNeelView Answer on Stackoverflow
Solution 2 - Javauser207421View Answer on Stackoverflow
Solution 3 - JavaLuis Manuel TavarezView Answer on Stackoverflow
Solution 4 - JavaJay PatelView Answer on Stackoverflow
Solution 5 - JavabretterView Answer on Stackoverflow
Solution 6 - JavajustAnotherGuyView Answer on Stackoverflow
Solution 7 - JavaSergey KalinichenkoView Answer on Stackoverflow
Solution 8 - Javauser2601995View Answer on Stackoverflow
Solution 9 - JavaRecurseView Answer on Stackoverflow
Solution 10 - JavaConkerJView Answer on Stackoverflow
Solution 11 - JavaGhulam MustafaView Answer on Stackoverflow