Rounding real numbers to X decimal places

Bill Baxter dnewsgroup at billbaxter.com
Fri Mar 9 12:12:55 PST 2007


jicman wrote:
> Greetings!
> 
> Forgive me for this stupid question, but I have searched all over digitalmars
> and std.math and I can not find a round(real,places) where real is a real
> number and places is an integer suggesting the decimal places to round to.  I
> had to do a subroutine for this using std.math.ceil() and some multiplication.
>  But, is there a function in std.math, or anywhere to do this?
> 
> thanks,
> 
> jos�

The lack of such a function probably has something to do with the fact 
that you can't represent 2.3 exactly in floating point.  But integers do 
have an exact representation.

There is a round() function in std.math though.  Something like this 
should work reasonably, as long as you don't let 'places' go too high.


static import std.math;
real round(real x, uint places)
{
    real pwr = pow(10.0,places);
    return std.math.round(x * pwr) / pwr;
}


--bb


More information about the Digitalmars-d-learn mailing list