The example in this article will answer the problem of retaining two decimal places in Java for your reference. The specific content is as follows
Method 1:
rounding
double f = 111231.5585; BigDecimal b = new BigDecimal(f); double f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
Method 1 This class solves the problems brought by Method 3 very well.
Keep two decimal places
Method 2:
DecimalFormat df =new DecimalFormat("#.00"); df.format(the number you want to format);Example: new DecimalFormat("#.00").format(3.1415926)
.00 means two decimal places #.00004 decimal places and so on...
Notice:
I used the above class and saw a data conversion exception. The reason is that a comma appears when String converts double, resulting in a conversion error. The decimal points of many European countries are represented by commas. 3.14 is not written in many European countries, such as France and the Netherlands, but 3,14. In these countries, what we call decimal points are expressed in commas. The separator characters of 333, 333, 333 are not represented by commas, but by dots, that is, 333.333.333. There are so many European and American countries, and the digital expression method in each country is not the same system.
Method 3:
double d = 3.1415926;String result = String .format("%.2f");%.2f %. Indicates: Any digit before the decimal point is 2. The result after two decimal format is f. Indicates floating point type
Method 4:
NumberFormat ddf1=NumberFormat.getNumberInstance(); void setMaximumFractionDigits(int digits)
digits The number of digits displayed is the most displayed digit after the format object is set to the decimal point, and the last digit displayed is rounded
Specific analysis:
//Return the default numerical format of the current default locale. String myString = NumberFormat.getInstance().format(myNumber); System.out.println(myString); //getCurrencyInstance() returns the general format of the current default locale myString = NumberFormat.getCurrencyInstance().format(myNumber); System.out.println(myString); //getNumberInstance() returns the general numerical format of the current default locale. myString = NumberFormat.getNumberInstance().format(myNumber); System.out.println(myString); //getPercentInstance() Returns the percentage format of the current default locale. myString = NumberFormat.getPercentInstance().format(test); System.out.println(myString); //setMaximumFractionDigits(int) Set the maximum number of digits allowed for the decimal part of the value //setMaximumIntegerDigits(int) Set the maximum number of digits allowed for the integer part of the value //setMinimumFractionDigits(int) Set the minimum number of digits allowed for the decimal part of the value //setMinimumIntegerDigits(int) Set the minimum number of digits allowed for the integer part of the value
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.