What is the round() function in D?

Overview

The round() function in D rounds a number off to the nearest integer.

  • If the fractional part >= 0.5 then the number is rounded up.
  • If the fractional part < 0.5 then the number is rounded down.

The image below shows a visual representation of the round() function:

Visual representation of the round() function

Note: Import std.math in your code to use the round() function. You can import it using import std.math.

Syntax

Syntax for the round() function is given below:


round(number)
// number should be float, double or real.

Parameter

This function requires a number as a parameter.

Return value

The round() function returns the nearest integer value of a number.

Note: If -0.0, real.infinity, real.infinity, real.nan, or -real.nan is sent as a parameter then it returns the parameter as it is.

Example

The code below shows the use of the round() function in D:

import core.stdc.stdio;
import std.stdio;
//header required for function
import std.math;
int main()
{
//integer
writeln ("The value of round(4.0) : ",round(4.0));
//positive double value
writeln ("The value of round(2.56) : ",round(2.56));
writeln ("The value of round(2.3) : ",round(2.3));
//negative double value
writeln ("The value of round(-2.56) : ",round(-2.56));
writeln ("The value of round(-2.3) : ",round(-2.3));
//exceptional outputs
writeln ("The value of round(-0.0) : ",round(-0.0));
writeln ("The value of round(real.infinity) : ",round(real.infinity));
writeln ("The value of round(-real.infinity) : ",round(-real.infinity));
writeln ("The value of round(real.nan) : ",round(real.nan));
writeln ("The value of round(-real.nan) : ",round(-real.nan));
return 0;
}

Explanation

  • Line 4: We add the header std.math required for the round() function.

  • Line 9: We round the integer value using round().

  • Line 12: We round the positive double value (fractional part >= 0.5) using round().

  • Line 13: We round the positive double value (fractional part < 0.5) using round().

  • Line 16: We round the negative double value (fractional part >= 0.5) using round().

  • Line 17: We round the negative double value (fractional part <= 0.5) using round().

  • Line 19: We round the exceptional numbers using round().

Free Resources