Powerbasic Museum 2020-B

IT-Consultant: Patrice Terrier => C++ programming (SDK style) => Topic started by: Patrice Terrier on October 21, 2014, 05:08:52 PM

Title: C++ float to int Banker's rounding
Post by: Patrice Terrier on October 21, 2014, 05:08:52 PM
As you probably know C/C++ doesn't have a built-in function to convert float to long using the Banker's algo.

Do you have one, rounding the same than PowerBASIC when converting float to long?

So far i am using this, but i don't know if it works exactly like PB

long roundL(IN float number) {
    return (long) floor(number + 0.5f);
}



...


Title: Re: C++ float to int Banker's rounding
Post by: Frederick J. Harris on October 27, 2014, 02:41:18 AM
I've never taken the time to look into it Patrice, but have occasionally had minor discrepencies in my algorithms because of it, i.e., discrepancies from PowerBASIC calculations.  It seems that sprintf and like functions round - and it wouldn't surprise me if whatever algorithm they use is/was similiar to Bob's.  In other words, lets say you have this number...

3.14159

...and you want that to four decimal places to the right of the decimal, instead of five.  So the 9 needs to go and the 5 at the fourth place needs to become a 6.  I haven't tested it, I'm just writing this off the top of my head, but I believe this would do it...

wchar_t szNumber[16];
double pi 3.14159;
wsprintf(szBuffer,L"%1.4f",pi);

I guess I ought to test it and see...

later

yea, it worked.  But then you'll need to convert it back to numeric format.  Its a pretty awkward workaround.  Better to use a real algorithm like you are looking for.


#include <cstdio>
#include <string>

int main()
{
wchar_t szNumber[16];
double pi = 3.14159;
swprintf(szNumber,L"%1.4f",pi);
wprintf(L"szNumber = %s\n",szNumber);

return 0;
}

/*
szNumber = 3.1416
*/
Title: Re: C++ float to int Banker's rounding
Post by: Patrice Terrier on October 27, 2014, 09:45:27 AM
The main problem i have been faced with, was when performing pixel calculation while zooming image.
I could never get exactly the same result in C++ and PowerBASIC when converting float to long.

For example
with Powerbasic
Local nLong as long, rFloat as single
rFloat = 4.51
nLong = CLNG(rFoat)
result nLong = 5

with C++
long nLong = 0;
float rFloat = 4.51
nLong =(long) (rFoat)
result nLong = 4

To let C++ give me the same result than PB, i had to use this:
nLong = (long) (rFloat + 0.5f);

...