Java: How to set Precision for double value? [duplicate]
Solution 1:
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:
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:
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:
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