March 09, 2007 Rounding real numbers to X decimal places | ||||
---|---|---|---|---|
| ||||
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é |
March 09, 2007 Re: Rounding real numbers to X decimal places | ||||
---|---|---|---|---|
| ||||
Posted in reply to jicman | 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
|
Copyright © 1999-2021 by the D Language Foundation