digitalmars.D.learn - Rounding real numbers to X decimal places
- jicman (8/8) Mar 09 2007 Greetings!
- Bill Baxter (13/24) Mar 09 2007 The lack of such a function probably has something to do with the fact
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é
Mar 09 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
Mar 09 2007