'Java Double object storing till two decimal places [duplicate]
Is it possible to store java.lang.Double to exactly two decimal places
Ex : 0.2 becomes 0.20
I modified the code to following
Double correlation = getSomeDoubleValue(label, key, date);
DecimalFormat df = new DecimalFormat("0.00");
correlation = Double.valueOf(df.format(correlation));
but when function getSomeDoubleValue() returns 0.2 , df.format(correlation) makes it 0.20 but as i need java.lang.Double , then Double.valueOf("0.20") gives me 0.2 back.
I am not sure how to achieve this or if its achievable at all.
Solution 1:[1]
Floating point numbers, such as double and float are really mathematical expressions and are inexact because of it.
If you want something more exact, you should use the BigDecimal class, which is an arbitrary precision decimal number.
You can set the number of places a BigDecimal stores by setting its scale using one of its setScale functions, which can also be used to set which rounding mode it uses when you do math operations on it.
Be aware that BigDecimal is an object type, so you need to use its methods to do math operations with it (.add, .subtract, .multiply, .divide).
BigDecimal has constructors for creating a BigDecimal from a double, long, or int.
Solution 2:[2]
A double with a value of 0.2 is storing the fact that the number is 0.20. In addition, it also represents the number 0.200, 0.2000, 0.20000, etc. What it sounds like you're looking for is a way to print out numbers to two decimal places of precision. To do this, see: Best way to Format a Double value to 2 Decimal places
Solution 3:[3]
Is this for storing money?
If so, use int or long and store the total number of cents. Then just move the decimal point when needed.
So instead of storing 0.20 you store 20 and when printing know to put the decimal point.
Solution 4:[4]
one way to get 0.2 as 0.20 is to store the value in String. e.g. String number = String.format("%.2f",correlation );
Solution 5:[5]
Your problem is not about precision. By default doubles in Java have a fixed precision which is far greater than 2 decimal places. I.E. the value is stored with more than 2 decimal places by default.
You can also take a look at this question
It seems to me that you are looking for a way to represent only 2 decimal digits. One way is by using printf
For example:
System.out.printf("%.2f", 0.2);
This will print:
0.20
Hope this helps
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Powerlord |
| Solution 2 | Community |
| Solution 3 | dkatzel |
| Solution 4 | Manoj |
| Solution 5 | Community |
