By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,657 Members | 1,094 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,657 IT Pros & Developers. It's quick & easy.

About round command?

P: n/a
I don't know how to write the code for round command?
For example if more than .5 then round up,if less than .5
round down such as 4.3 round to 4.0 and 5.5 round to 6.0
Nov 16 '05 #1
Share this Question
Share on Google+
4 Replies


P: n/a

There are lots of solutions to this.

If you would like to make your own round-function take a look at the modulo
function %.

Have you seen the
Math::Round(3.44, 1); //Returns 3.4.
Math::Round(3.45, 1); //Returns 3.4.
Math::Round(3.46, 1); //Returns 3.5.

in the .Net framework?
--
Regards,
Lars-Inge Tonnessen
http://emailme.larsinge.com
http://www.larsinge.com

Nov 16 '05 #2

P: n/a
Lars-Inge Tønnessen wrote:
There are lots of solutions to this.

If you would like to make your own round-function take a look at the modulo
function %.


% is an operator, not a function, and it is not defined for non-integral
types.

Gerhard Menzl

Nov 16 '05 #3

P: n/a
Sin
> I don't know how to write the code for round command?
For example if more than .5 then round up,if less than .5
round down such as 4.3 round to 4.0 and 5.5 round to 6.0


A simple trick is to add 0.5 to the value (if positive) or remove 0.5 (if
negative). By converting the value back into an integer it will
automatically round to the right value.

Ex:

4.0 + 0.5 = 4.5... truncated (cast) = 4.0
4.3 + 0.5 = 4.8... truncated (cast) = 4.0
4.5 + 0.5 = 5.0... truncated (cast) = 5.0
4.7 + 0.5 = 5.2... truncated (cast) = 5.0

Here's a macro that implements the "logic" :

#define ROUND_INT(x) ((int)((x)+(((x)>0)?0.5:-0.5)))

If you need it for a float/double, just cast back into one...

Alex.
Nov 16 '05 #4

P: n/a
This is where your programming creativity comes in when you develop your own
function/method/class. =:o)

--
Regards,
Lars-Inge Tonnessen
http://emailme.larsinge.com
http://www.larsinge.com
Nov 16 '05 #5

This discussion thread is closed

Replies have been disabled for this discussion.