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.5then the number is rounded up. - If the
fractional part < 0.5then the number is rounded down.
The image below shows a visual representation of the round() function:
Note: Import
std.mathin your code to use theround()function. You can import it usingimport 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.nanis 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 functionimport std.math;int main(){//integerwriteln ("The value of round(4.0) : ",round(4.0));//positive double valuewriteln ("The value of round(2.56) : ",round(2.56));writeln ("The value of round(2.3) : ",round(2.3));//negative double valuewriteln ("The value of round(-2.56) : ",round(-2.56));writeln ("The value of round(-2.3) : ",round(-2.3));//exceptional outputswriteln ("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.mathrequired for theround()function. -
Line 9: We round the integer value using
round(). -
Line 12: We round the positive double value (
fractional part >= 0.5) usinground().
-
Line 13: We round the positive double value (
fractional part < 0.5) usinground(). -
Line 16: We round the negative double value (
fractional part >= 0.5) usinground(). -
Line 17: We round the negative double value (
fractional part <= 0.5) usinground(). -
Line 19: We round the
exceptional numbersusinground().