About round command?

  • Thread starter Thread starter hamster
  • Start date Start date
H

hamster

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
 
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?
 
Lars-Inge Tønnessen said:
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
 
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.
 
This is where your programming creativity comes in when you develop your own
function/method/class. =:o)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

News CES 2019 round up 6
Round Function 5
Round formula 1
Possible router problems 9
Arch Wins 10
Windows 7 Internet Access 3
Formula help 1
Rounding 3

Back
Top