Home >Java >javaTutorial >How to use round function in java

How to use round function in java

下次还敢
下次还敢Original
2024-04-27 01:48:16619browse

The round() function in Java rounds floating point numbers to the nearest integer, following the following rules: 1. Positive numbers are rounded to the nearest even number; 2. Negative numbers are rounded to the nearest even number; 3. When the decimal part is 0.5, round to the nearest even number.

How to use round function in java

Usage of round() function in Java

round() function overview

The round() function in Java is used to round floating point numbers to the nearest integer. This function accepts a floating point number as a parameter and returns a long value representing the rounded integer.

Syntax

<code class="java">public static long round(double a)</code>

Parameters

  • a - The floating point number to be rounded

Return value

  • The rounded integer, type is long

Rounding rules

The round() function follows the following rounding rules:

  • Positive numbers: If the decimal part of the floating point number is greater than or equal to 0.5, it is rounded to the nearest even number .
  • Negative numbers: If the decimal part of the floating point number is less than 0.5, it is rounded to the nearest even number. If the fractional part is equal to 0.5, then round to the nearest even number.

Example

The following example demonstrates how to use the round() function:

<code class="java">double num1 = 12.5;
double num2 = -13.7;

long roundedNum1 = Math.round(num1); // 12
long roundedNum2 = Math.round(num2); // -14</code>

In this example:

  • num1 is rounded to 12 because the fractional part 0.5 is greater than or equal to 0.5.
  • num2 is rounded to -14 because the fractional part 0.7 is less than 0.5.

The above is the detailed content of How to use round function in java. 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