Rounding, and converting double to int

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.
which is really the correct way!
No, it isn't.
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.
(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?
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
helios +1
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
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.
Of course you have ceiling() and floor()
That's not rounding. That's truncation.
Topic archived. No new replies allowed.