Home > Java > javaTutorial > body text

How to use round function in java

下次还敢
Release: 2024-04-27 01:48:16
Original
545 people have browsed it

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>
Copy after login

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>
Copy after login

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!