Rounding, and converting double to int

Feb 23, 2010 at 3:48pm
Hello there,

I am trying to convert a double type into an integer; which in itself isn't too much of a problem.

The problem I am facing is trying to round my numbers, I would use the round() function however, when a number is exactly halfway (1.5) for example I would like it to round down instead of up (which is really the correct way!)

I found a tutorial, however that seems to show what I want to do; however I can't get the thing to work, and cannot for the life of me get my head around it!

Thanks for the help guys.
Feb 23, 2010 at 4:29pm
which is really the correct way!
No, it isn't.
Feb 23, 2010 at 4:36pm
What method of rounding are you using? It certainly doesn't match any method of rounding I've ever seen. Rounding .5 up is one of the most common methods used.
Feb 23, 2010 at 4:39pm
(1.5) for example I would like it to round down instead of up


OK

(which is really the correct way!)


???

Anyway, couldn't use just use round() for all numbers except for those within a very small distance of 1.5?
Feb 23, 2010 at 5:08pm
Hi dannn,

simply subtract 0.5 from your number and then compute the ceiling of the result:

1
2
3
4
5
int
roundHalfwayDown(double d)
{
	return ceil(d - 0.5);
}


This works fine with g++ 4.4.1 (ubuntu).

Cheers,
TheBear
Feb 23, 2010 at 10:39pm
Feb 23, 2010 at 11:47pm
helios +1
Feb 24, 2010 at 12:19am
There is no "one true way to round." All that matters is the kind of bias you want. See the article I linked.

[edit] We were all taught in gradeschool "arithmetic rounding", or common rounding, which is x>=.5 round up, x<.5 round down. [/edit]
Last edited on Feb 24, 2010 at 12:20am
Feb 24, 2010 at 12:23am
Exactly, arithmetic rounding is the mathematically correct way to round. That's why I ++'d helios. He was right. Of course you have ceiling() and floor() but if you can round in either direction, .5 and up should be rounded up.
Feb 24, 2010 at 12:31am
Of course you have ceiling() and floor()
That's not rounding. That's truncation.
Topic archived. No new replies allowed.