[Issue 12547] floor/round/ceil that optionally return a specified integral type

d-bugmail at puremagic.com d-bugmail at puremagic.com
Fri Apr 11 04:48:27 PDT 2014


https://issues.dlang.org/show_bug.cgi?id=12547

--- Comment #2 from bearophile_hugs at eml.cc ---
(In reply to Don from comment #1)

> FYI: They are defined to return floating-point values because that's what
> the equivalent C functions do. They should not be modified.

Perhaps lovers of C functions can use core.stdc.math:

void main() {
    import core.stdc.math;
    double x = 2.7;
    int y1 = cast(int)floor(x);
    int y2 = cast(int)ceil(x);
    int y3 = cast(int)round(x);
}


But perhaps new functions can be defined in Phobos, with a different name
(possibly with a clear name).


> Note that if you cast them to integers, you have to worry about overflow. So
> that's more complicated.

In the cases where you care about overflow can't you use to! function?


void main() {
    import std.math, std.conv;
    double x = 1e100;
    int y1 = x.floor.to!int;
}


> Note also the existence of rndint() and rndlong().

I don't know where they are, sorry for my ignorance. Do you mean stuff like
this?
http://opensource.apple.com/source/Libm/Libm-93/ppc.subproj/rndint.c

In std.math I have found this:

pure nothrow @safe long rndtol(real x);
    Returns x rounded to a long value using the current rounding mode. If the
integer value of x is greater than long.max, the result is indeterminate.

But what about ints, or floor/ceil? (And usually functions with name that
starts with "rnd" are for random generation).

Thank you Don for your answers.

--


More information about the Digitalmars-d-bugs mailing list