In the actual development, we relative some division after the result of simple output, or customized display effect, the following several methods for reference (full text to retain two decimal as an example) :
First, format the decimal method
1. Format printf output
For students who have learned C language, this method is not strange! Mainly use printf to format the output:
double ll =len/(1024*1024.0);
System.out.println("File size is"+ll+"MB");/ / 36.364097595214844
System.out.printf("%.2f",ll);/ / 33.36
Copy the code
2. DecimalFormat classes
This method is not common for beginners because it involves the DecimalFormat class and is not friendly enough
DecimalFormat d = new DecimalFormat("00 #.");
System.out.println(d.format(ll));/ / 36.36
Copy the code
3. Perform operations
By calculating, you move the decimal a few places back, keep the integer, and then divide by the number of digits you move back, giving you exactly the number of digits you want to keep
System.out.println((int)(ll*100) /100.0);/ / 36.36
Copy the code
The above does not guarantee rounding, if you need to round the exact value, continue:
Two, keep 2 decimal places round as an example
(1). Use the BigDecimal class
Public BigDecimal setScale(int newScale, int roundingMode) // newScale is the number of digits reserved after the decimal point, roundingMode is the variable selection method; The BigDecimal.ROUND_HALF_UP attribute indicates rounding
double f = 3.1415;
BigDecimal bd = new BigDecimal(f);
double f1 = bd.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue(); The output f1 is3.14;Copy the code
(2). DecimalFormat classes use
#.00 represents two decimal places. #.0000 represents four decimal places and so on…
String format = new DecimalFormat("#.0000").format(3.1415926); System.out.println(format); The output is3.1416
Copy the code
(3). The String. Format method
In %.2f, %. Indicates any number of digits before the decimal point.2 indicates the result of the two-digit decimal format.
double num = 3.1415926;
String result = String.format("%.4f", num); System.out.println(result); The output is:3.1416
Copy the code
(4).
The 0.01d of the final product represents the number of digits to be retained after the decimal point (rounded), 0.0001 represents the number of digits to be retained after the decimal point, and so on…
double num = Math.round(3.141592 * 100) * 0.01 d; System.out.println(num); The output is:3.14
Copy the code
If need to reprint, please note the link!