This article takes the retention of two decimal places as an example. If you have other requirements, you can easily change them.
1. Use Java. Text. decimalformat (recommended)
Java. Text. decimalformat df = new java. Text. decimalformat ("#. 00 ");
DF. Format (number );
Eg:
New decimalformat ("#. 00"). Format (3.1415926) // #. 00 indicates two decimal places #. 0000 four decimal places, and so on.
2. Algorithm Implementation
Double result = (INT) (Number * 100)/100.0;
3. Implementation using the bigdecimal Method
Double F = 111231.5585;
Bigdecimal B = new bigdecimal (f );
Double result = B. setscale (2, bigdecimal. round_half_up). doublevalue ();
Retain two decimal places
4. Use the setmaximumfractiondigits method of numberformat to implement
Numberformat format = numberformat. getnumberinstance ();
Format. setmaximumfractiondigits (INT digits) // digits is the number of digits displayed.
Note: The maximum number of digits displayed after the decimal point is set for the formatted object. The last digit is rounded.
Eg:
import java.text.* ;public class Formula2 {
public static void main(String[] args) { double number = 23.5455; NumberFormat format = NumberFormat.getNumberInstance() ; format.setMaximumFractionDigits(2); String result = format.format(number) ; System.out.print(result);
}}
Result: 23.55