Home > Common Problem > Java rounding method

Java rounding method

zbt
Release: 2023-11-14 10:23:59
Original
1511 people have browsed it

java uses the DecimalFormat class to create a formatting object decimalFormat and specify the format mode "#.##" that retains two decimal places. Then, use the format() method to format the floating point number into a string and convert it to a double type for rounding.

Java rounding method

#In Java, you can use the Math.round() method to achieve rounding. The Math.round() method accepts a floating point number as argument and rounds it to the nearest integer.

The following is a sample code for rounding using the Math.round() method:

double number = 3.6;
long roundedNumber = Math.round(number);
System.out.println("四舍五入后的结果为:" + roundedNumber);
Copy after login

The output is:

四舍五入后的结果为:4
Copy after login

In the above code, the floating point number 3.6 is passed Round the Math.round() method and assign the result to a long integer variable roundedNumber. Then, use the System.out.println() method to print the results to the console.

Please note that the Math.round() method returns a long integer value, so it needs to be converted to the required data type, such as integer or floating point, for further processing or show.

In addition, if you need to specify the number of decimal places to retain and round off, you can use the DecimalFormat class to achieve this. The following is a sample code:

import java.text.DecimalFormat;
double number = 3.6789;
DecimalFormat decimalFormat = new DecimalFormat("#.##");
double roundedNumber = Double.parseDouble(decimalFormat.format(number));
System.out.println("四舍五入后的结果为:" + roundedNumber);
Copy after login

The output result is:

四舍五入后的结果为:3.68
Copy after login

In the above code, use the DecimalFormat class to create a formatting object decimalFormat and specify the format mode that retains two decimal places"# .##". Then, use the format() method to format the floating point number into a string and convert it to a double type for rounding.

The above is the detailed content of Java rounding method. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template