About Java how two decimal places
First, call the format method of the String class when printing is set to retain the number of bits (simple and easy)
Second, create DecimalFormat object to implement the digital print reservations digits (create an object and more than a second)
Third, create a BigDecimal object operational set up a reservation digits. (This method is not practical sense)
A, String.format
double d1 = 6.6666;
double d2 = 8.88888;
double d3 = 3;
System.out.println(String.format("%.2f", d1));//设置保留两位小数
System.out.println(String.format("%.2f", d2));
System.out.println(String.format("%.2f", d3));
//注意:没有小数位或者小数位不够你设置的保留数时,自动补0
二、DecimalFormat
double d1 = 6.6666;
double d2 = 8.88888;
double d3 = 3;
DecimalFormat df = new DecimalFormat("#.00");//设置保留两位小数
System.out.println(df.format(d1));
System.out.println(df.format(d2));
System.out.println(df.format(d3));
三、BigDecimal
- Position : java.math package
- Action : exact floating-point number
- Creating ways : BigDecimal bd = new BigDecimal ( " 1.0");
- Methods :
- BigDecimal add(BigDecimal bd)
- BigDecimal subtract(BigDecimal bd)
- BigDecimal multiply(BigDecimal bd)
- BigDecimal divide(BigDecimal bd)
May be performed using the numerical BigDecimal
- 除法:BigDecimal(BigDecimal bd, int scal, RoundingMode mode)
- Parameters SCAL : Specifies the accuracy of several decimal places
- Parameters the MODE :
- Mode choice specified fractional part, rounding is usually employed mode
- Value of BigDecimal.ROUND_HALF_UP