• A Wizard A True Star (cs)

I bet RoundCorrect3, when it's eventually written, will use this obscure function known as abs() to allow for the possibility of negative numbers. Innovation!

• php user (unregistered)

So, what's wrong with just using round()?

• mlathe (cs) in reply to php user

Anonymous:
So, what's wrong with just using round()?

maybe it doesn't exist?

• koning_robot (unregistered) in reply to php user
Anonymous:
So, what's wrong with just using round()?

PHP also features better_round(), which is a better round().
• ferrengi (cs)

OK,
So he wrote one function which I cannot follow the logic of and figure out what it does but suffice to say that it can't possibly be a good solution. Then he came up with something which seems to round down to the nearest whole number if the decimal portion is < .01
If the decimal portion is greater than .01, the number gets rounded up to the nearest whole number.
A great way to "round off"!

Now, to correct this problem, he decides to use .5 as the cutoff. Much better than the first two attempts. This actually seems to work correctly for numbers with only one decimal place. So, what function needs to be called if the number needs to be rounded off to the nearest few decimal places instead of the nearest whole number? Is there a function RoundCorrect3() that deals with rounding to one decimal place and RoundCorrect4() to deal with rounding to 2 places? etc...

And what happened to the globalRounding variable. Why was it taken out of the second and third rendition of this function?

That's what I was able to come up with.

• mlq (unregistered) in reply to php user

If everybody just went off and used round(), then we'd have nobody to mock.  Personally, I am thankful for those who exist only to serve as warnings to others.

• AlpineR (cs)

I'd just like to point out that there are many kinds of rounding. I'm afraid to guess which one this code is attempting to implement.

• R K Quinlivan (unregistered)

Was this written by someone with a college degree?! Good lord, I am going to have to work with these people some day. :-(

• Great Griff (unregistered) in reply to php user

There's lots of reasons to never use a language's built in rounding function. Mainly it will never do what your users want. People (and the government, especially the IRS) are passionate about rounding and there are many, many ways of doing it:

Look at all the different ways to round: http://www.pldesignline.com/howto/showArticle.jhtml;?articleID=175801189

• boohiss (unregistered) in reply to mlq

I wish ASP VBScript had floor and ceiling functions. I have to write a 5 line 'if' statement everytime I want the ceiling of something.

• mlathe (cs)

float Round(float val)
{
TCHAR tmpStr[128];
int intVal, decVal;
int i;

if(globalRounding)
{
_stprintf(tmpStr, _T("%0.1f"), val);
intVal = _ttoi(tmpStr);

for(i = 0; i < (int)_tcslen(tmpStr); i ++)
{
if(tmpStr[i] < '0' || tmpStr[i] > '9')
{
decVal = _ttoi(&(tmpStr[i + 1]));
}
}
if(decVal <= 3)
{
val = (float)intVal;
}
}
return val;
}

Correct me if i'm wrong. But the Round function seems to isolate the decimal point and get the next char. If that is <=3 then round down, else just return the origional number.

thus:
1.2 ==> 1.0
1.3 ==> 1.0
1.4 ==> 1.4
1.9 ==> 1.9

not a very good rounding function!

also why does Round return a float?

• Disgruntled DBA (cs)

They all said it was daft to write a rounding function in C.  So, just to show 'em, I built it anyway.  The first rounding function sank into the swamp.  So I built a second rounding function, and that sank into the swamp.  I built a third rounding function, and that burned down, fell over, and then sank into the swamp, but the fourth one stood up, and that's what you're getting, lad.  The strongest rounding function in these isles.....

• TankerJoe (cs)

`  if(globalRounding)`

The real WTF here is that he keeps a global flag to tell if he should acctually do any rounding.

In addition... he forgot to write that into his follow up functions.  WTF
• lucky luke (cs)

```int RoundCorrect(float number)
{
if(number-(int)number<0.01)
return (int)number;
else
return (int)(number+1);
}```

maybe... just maybe in RoundCorrect() he thought that number - (int)number would somehow cast the returned value to be an int too and be magically rounded already thus if the number was close to 0 it would be rounded down and the other possible value would have been 1. So instead of writing == 0 he wrote < 0.01
I mean really who hasn't defined 0 as being < 0.01

A Wizard A True Star
``````								: abs()&nbsp; you mean they finally installed an antilock braking system for programs so they won't freeze up? ~ or is that a windows only thing </span><a href="">;)</a>
``````
• JAlexoid (unregistered) in reply to ferrengi

I would have to confess that I too did theese function, but they did serve a purpose the accomodates the rounding practices of the company's accountants. And I have to have exact VAT sum calculated and it may be WAY OFF when VAT is 18%.

• grmcdorman (unregistered)

Take a closer look at the first "rounding" function - specifically, what it will do for numbers like 1.01 and 1.007:
1.01 -> 1
1.007 -> 1.007
(ttoi will ignore leading zeros, so 01, 0001, and 00001 are all the same value: 1)

• Strydyr (cs)

Assuming there's no Round function:

(int) (number + 0.5)

should get the job done.

In fact 0.5 could instead be a global variable, so that "correctness" can be tweaked on the fly!

• a goat (unregistered) in reply to Great Griff
Anonymous:

There's lots of reasons to never use a language's built in rounding function. Mainly it will never do what your users want. People (and the government, especially the IRS) are passionate about rounding and there are many, many ways of doing it:

Look at all the different ways to round: http://www.pldesignline.com/howto/showArticle.jhtml;?articleID=175801189

I don't see Bankers' Rounding in that list.  I've had to do the rounding function in C# because the C# Math.Round() function performs Bankers' Rounding and the spec said to use Round Half Up rounding (ironically enough, this was at a Bank)

Bankers' Rounding is essentially Round Half Towards Nearest Even

3.4 goes to 3

3.5 goes to 4

3.6 goes to 4

4.4 goes to 4

4.5 goes to 4

4.6 goes to 5

• a goat (unregistered) in reply to Great Griff
Anonymous:

There's lots of reasons to never use a language's built in rounding function. Mainly it will never do what your users want. People (and the government, especially the IRS) are passionate about rounding and there are many, many ways of doing it:

Look at all the different ways to round: http://www.pldesignline.com/howto/showArticle.jhtml;?articleID=175801189

oops, just found it

• GoatCheez (cs) in reply to Strydyr
Strydyr:

Assuming there's no Round function:

(int) (number + 0.5)

should get the job done.

In fact 0.5 could instead be a global variable, so that "correctness" can be tweaked on the fly!

If there is an abs(), then it should use it too... negative values often get overlooked in rounding functions... I usually do something like:

return (number > 0)?((int)(number+ 0.5)):((int)(number-0.5));
• MePogo (unregistered) in reply to R K Quinlivan
Anonymous:
Was this written by someone with a college degree?! Good lord, I am going to have to work with these people some day. :-(

One of these days, I'm going to _be_ one of these people...
• CornedBee (cs) in reply to GoatCheez
GoatCheez:

If there is an abs(), then it should use it too... negative values often get overlooked in rounding functions... I usually do something like:

return (number > 0)?((int)(number+ 0.5)):((int)(number-0.5));

That's one superfluous cast:

`return (int)((number > 0) ? (number + .5) : (number - .5));`
• Alun Jones (unregistered) in reply to GoatCheez

GoatCheez:

If there is an abs(), then it should use it too... negative values often get overlooked in rounding functions... I usually do something like:

return (number > 0)?((int)(number+ 0.5)):((int)(number-0.5));

I once worked on a program that had, for ten years, been used by companies controlling multi-million dollar projects to the accuracy of one penny.  Reading from a dBase file, and converting all decimals to pseudo-"fixed point" integers, the code included sections like this:

FIXEDPOINT = INTEGRAL_PART * 10 ** MANTISSA + FRACTIONAL_PART

(Yes, that's FROTRAN)

That's great for positive numbers - "10.03" goes to 10 * 10^2 + 3 = 1003.

But for negative numbers, "-10.03" goes to -10*10^2+3 = -9997.

Even after demonstrating this to the original developer of the code (and president of the company), he refused to acknowledge that it existed, and I had to fix it in stealth-mode.

In another project, I wrote two functions for evaluating the "British Standard for Roundness", but I don't think this is the kind of round they were talking about.

• hermit (unregistered)

I HATE YOU

• ferrengi (cs) in reply to hermit
Anonymous:
I HATE YOU

Who?
• sao (cs) in reply to Disgruntled DBA
Disgruntled DBA:
They all said it was daft to write a rounding function in C.  So, just to show 'em, I built it anyway.  The first rounding function sank into the swamp.  So I built a second rounding function, and that sank into the swamp.  I built a third rounding function, and that burned down, fell over, and then sank into the swamp, but the fourth one stood up, and that's what you're getting, lad.  The strongest rounding function in these isles.....

FIRST!!.... post to make me laugh  ;-)

good job! =)
• GoatCheez (cs) in reply to CornedBee
CornedBee:
GoatCheez:

If there is an abs(), then it should use it too... negative values often get overlooked in rounding functions... I usually do something like:

return (number > 0)?((int)(number+ 0.5)):((int)(number-0.5));

That's one superfluous cast:

`return (int)((number > 0) ? (number + .5) : (number - .5));`

Of course, why not just go further with:
return (int) (number + ((number > 0)?0.5:-0.5));
• Otto (cs)

When writing financial applications, I prefer to use trunc(). Then I take whatever is truncated and add it to my own account.

I got the idea from Superman 3.

• DrDoom (unregistered) in reply to php user

Some programmers are reluctant to use in-build rounding functions for historical reasons. Those being that some CPUs and/or <?xml:namespace prefix = st1 ns = "urn:schemas-microsoft-com:office:smarttags" /><st1:City w:st="on"><st1:place w:st="on">OSs</st1:place></st1:City> chose different ways to round. That is some rounded up while some rounded down. As a result you could get 0.5 coming up as 0 on some test systems and 1 on others.

Of course there are always those that don’t know what they are doing or need to justify 100 hours overtime for solving a complicated problem but do not have any code to show for it.

• et tu? (unregistered) in reply to DrDoom

Sometimes I just like to imagine what I would do if I were the manager and decided to do a code review and found something like this (instead of having to clean it up, like I do now).  The first instinct, of course, is to call security and have the offending "developer" escorted out of the building, into the back alley, and beaten within an inch of his life.  That might make me feel better, but would he have really learned his lesson?

Let's take another approach.  Give the developer a laptop, throw him in a room with no Internet connection, and order him not to leave until he has a 100% fully functional, well tested (with test result output available) rounding function or failing that, a resignation letter explaining that he really doesn't know how to code and we will never see or hear from him again.  We will then frame his resignation letter and show it to all new hires when we make them a job offer, with the added clause that if they regularly produce code of this quality, they will owe the company every single dollar that we have ever paid them, with interest.

• DerGuteMoritz (cs) in reply to Disgruntled DBA

But all I want to do is striiiiiiiiiiiiing manipulation!

• Gene Wirchenko (cs) in reply to et tu?
Anonymous:
Sometimes I just like to imagine what I would do if I were the manager and decided to do a code review and found something like this (instead of having to clean it up, like I do now).  The first instinct, of course, is to call security and have the offending "developer" escorted out of the building, into the back alley, and beaten within an inch of his life.  That might make me feel better, but would he have really learned his lesson?

Could he ever?

Let's take another approach.  Give the developer a laptop, throw him in a room with no Internet connection, and order him not to leave until he has a 100% fully functional, well tested (with test result output available) rounding function or failing that, a resignation letter explaining that he really doesn't know how to code and we will never see or hear from him again.  We will then frame his resignation letter and show it to all new hires when we make them a job offer, with the added clause that if they regularly produce code of this quality, they will owe the company every single dollar that we have ever paid them, with interest.

That will not work.  With an employee, you can not refuse to pay them for their time.

You definitely have an extreme approach.  I wish it were not so justified.

Sincerely,

Gene Wirchenko

• php user (unregistered) in reply to koning_robot
Anonymous:
PHP also features better_round(), which is a better round().

Umm, no it doesn't.
• Stoffel (cs) in reply to Great Griff
Anonymous:

There's lots of reasons to never use a language's built in rounding function. Mainly it will never do what your users want. People (and the government, especially the IRS) are passionate about rounding and there are many, many ways of doing it:

Look at all the different ways to round: http://www.pldesignline.com/howto/showArticle.jhtml;?articleID=175801189

Excellent point.  Video and audio coding specs usually have some sort of convention like:
/ - divide w/ truncation
// - divide w/ round toward -inf
/// - divide w/ round toward 0

etc.  I saw it get up to 4 slashes once.  So A / B != A //// B for all values of A & B.
• Stoffel (cs) in reply to Stoffel

er, make that for some values.

• BtM (unregistered) in reply to GoatCheez
GoatCheez:
Strydyr:

Assuming there's no Round function:

(int) (number + 0.5)

should get the job done.

In fact 0.5 could instead be a global variable, so that "correctness" can be tweaked on the fly!

If there is an abs(), then it should use it too... negative values often get overlooked in rounding functions... I usually do something like:

return (number > 0)?((int)(number+ 0.5)):((int)(number-0.5));

What if you're rounding a value that's greater than INT_MAX?

It's the corner cases that you have to watch out for...
• sao (cs) in reply to BtM

tmpint = ((number > 0)?((int)(number+ 0.5)):((int)(number-0.5)));
tmpint > maxint ? throw Exception("Arrrrrrgggggggg.....");
return tmpint;

and i dont care if the syntax is wrong.

• BiggBru (cs)

<FONT face=Georgia>I'm sure he'll have things figured out by the time RoundCorrect5() comes along...</FONT>

<FONT face=Georgia>By the way, are the C/C++ built-in rounding functions terrible enough to justify... this?</FONT>

• no name (unregistered) in reply to sao
tmpint = ((number > 0)?((int)(number+ 0.5)):((int)(number-0.5)));
tmpint > maxint ? throw Exception("Arrrrrrgggggggg.....");
return tmpint;

WTF???
• zephc (cs)

Sometimes bad code is just tiring to look at. Not that it is difficult, but trying to figure out "Why The F***?!?", if just becomes exhausting. This is one of them.

• dent (unregistered) in reply to boohiss
Anonymous:
I wish ASP VBScript had floor and ceiling functions. I have to write a 5 line 'if' statement everytime I want the ceiling of something.

It does have the ability to create your own functions though, doesn't it?  ;)
• josh (unregistered) in reply to GoatCheez
GoatCheez:
Of course, why not just go further with:
return (int) (number + ((number > 0)?0.5:-0.5));

pff.

return (int)(number + (number > 0) - 0.5);
• isostar (cs) in reply to BiggBru

There are no built in rounding functions in C.

• Rolf (unregistered) in reply to no name
Anonymous:
tmpint = ((number > 0)?((int)(number+ 0.5)):((int)(number-0.5)));
tmpint > maxint ? throw Exception("Arrrrrrgggggggg.....");
return tmpint;

WTF???

"The castle of .. aarrrgg....."
• gannimo (unregistered) in reply to sao

I don't think, you can test if an int value is bigger than the biggest possible int value ;)

• dhromed (cs) in reply to gannimo
Anonymous:
I don't think, you can test if an int value is bigger than the biggest possible int value ;)

One might as well use the literal False.
• guest (unregistered) in reply to josh
pff.

return (int)(number + (number > 0) - 0.5);

Don't do this in VB. True is not what you think it is :)

• teedyay (cs) in reply to et tu?
Anonymous:
Let's take another approach.  Give the developer a laptop, throw him in a room with no Internet connection, and order him not to leave until he has a 100% fully functional, well tested (with test result output available) rounding function or failing that, a resignation letter explaining that he really doesn't know how to code and we will never see or hear from him again.  We will then frame his resignation letter and show it to all new hires when we make them a job offer, with the added clause that if they regularly produce code of this quality, they will owe the company every single dollar that we have ever paid them, with interest.

^ This.

Anonymous:
I've had to do the rounding function in C# because the C# Math.Round() function performs Bankers' Rounding and the spec said to use Round Half Up rounding (ironically enough, this was at a Bank)

Yeah, me too. After a nightmare project or two, we've taken to explaining to the client up front about the different types of rounding, telling them that Bankers' rounding is (apparently) the standard, and asking them which type they'd like us to use. So far we've not met anyone (even in accounts departments) who has even heard of Bankers' rounding, and they've always gone for if-it's-a-half-round-up.

We also try to pre-empt their whinges about rounding errors (mostly occurring from our painful 17.5% VAT system), and manage to bring them down from their initial position of "we want everything to add up exactly to the penny in every circumstance, and we don't want to see any fractions of pence" before we write a single line of code.
• Dagur (unregistered)

There's nothing wrong with using sprintf. In fact that's the recommended way in the perl cookbook.

I don't get what that guy is doing in that function though.

• johnl (cs) in reply to teedyay

Let's take another approach.  Give the developer a laptop, throw him in a room with no Internet connection, and order him not to leave until he has a 100% fully functional, well tested (with test result output available) rounding function or failing that, a resignation letter explaining that he really doesn't know how to code and we will never see or hear from him again.  We will then frame his resignation letter and show it to all new hires when we make them a job offer, with the added clause that if they regularly produce code of this quality, they will owe the company every single dollar that we have ever paid them, with interest.

So in order to get him to develop a working function, you want to remove the ability to do this: http://www.google.co.uk/search?q=c%23+rounding , right?  Maybe you should hand in your letter of resignation along with him.

And before coming to this site, I'd never heard of Bankers' rounding.  I had to look it up again to know what we were talking about.