Home  >  Article  >  Java rounding method

Java rounding method

zbt
zbtOriginal
2023-11-14 10:23:591261browse

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);

The output is:

四舍五入后的结果为:4

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);

The output result is:

四舍五入后的结果为:3.68

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!

Statement:
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