(Reproduced from Xuan Ying Chi Yuzhou)
When doing a Java project, you may often encounter the question of preserving decimals for double type variables, and here is a brief summary of my experience:
In Java, a double type variable retains a decimal problem in two broad cases:
(i): the number of digits after the decimal point is too long, rounding retains the specified number of digits:
Can be implemented with the following code:
public class Testdemo {
public static void Main (string[] args) {
Double a=15.32743859;
Double B=math.round (a*10000)/10000.0000;//reserved Four decimal places
System.out.println (b);
}
}
To preserve n decimal places, it is Math.Round (n-a*10)/10 N-th square. N x 0.
(b): If the decimal point after the bottom is not shown in 0,myeclipse, such as
Double a=15.80;
System.out.print (a);
The result of the output in the console is 15.8.
And we sometimes want to show the percentile of 0, such as the display of commodity prices, generally display two decimal places, if the commodity price is 15.8, also shown as 15.80, if the commodity price is 15, also shown as 15.00, this situation, with (a) the method can not be achieved, how should be achieved?
Take a look at the following code:
Import Java.text.DecimalFormat;
public class Testdemo {
public static void Main (string[] args) {
DecimalFormat DF =new DecimalFormat ("# # #0.00");
Double a=15;
System.out.println (Df.format (a));
}
}
This way, even if our double type variable is 15, the display is also 15.00. Of course, we want to show how many digits are in the "# # #0.00" point to control the number of 0 can be. If it is "# # # #0", then our double variable, either 15.0 or 15.00, can be displayed as 15, and if our double variable is 15.60, it is shown as 16, that is, this method can also be rounded. It contains the function of (a), so we can choose this method in both cases.
PostScript: I encountered this problem when I was doing the U1 Project supermarket cashier management system. In the later stage of the testing, I found that the items in the project price of the place is generally displayed as a decimal, and in real life is generally reserved two decimal places. So painstakingly modified: constantly adjust the value of the XML, give the double variable initial value 0.00, with Math.Round () ... And so on, and so on, have not achieved the desired effect, make oneself confused. The teacher's "special treatment" of the Key Tips to guide me to continue to find the answer to the question, spent most of the day to solve. said that this week has become a "bug" week, all kinds of bad, all kinds of debugging, really difficult. However, I still believe that: do not be afraid of mistakes, do not fear the problem, to the pain in the process of solving problems to increase the experience value. Steady maybe just after the end of the rope.
Double variables in Java retain decimal problems