[Conversion] numeric_cast from floating to integral types
Hi all, I just discovered (by debugging instead of reading :-() that a numeric_cast from a floating to an integral type always truncates by default, that is, 26.99999 is casted to 26. Is there a way to tell numeric_cast to use the nearest integer? Of course I can add 0.5 to my value and cast afterwards but that's definitely ugly. Thanks in advance. Best regards, Rainer
Hi Rainer, Sorry I just saw this.
Hi all,
I just discovered (by debugging instead of reading :-() that a numeric_cast from a floating to an integral type always truncates by default, that is, 26.99999 is casted to 26. Is there a way to tell numeric_cast to use the nearest integer? Of course I can add 0.5 to my value and cast afterwards but that's definitely ugly.
numeric_cast<> uses the default policies, but you an easily create you own
version with any other policy, like the one which rounds floats to the
nearest integer: RoundEven<>
#include Converter ; return Converter::convert(arg);
}
HTH
--
Fernando Cacciola
SciSoft
http://scisoft-consulting.com
http://fcacciola.50webs.com
http://groups.google.com/group/cppba
Fernando Cacciola wrote:
I just discovered (by debugging instead of reading :-() that a numeric_cast from a floating to an integral type always truncates by default, that is, 26.99999 is casted to 26. Is there a way to tell numeric_cast to use the nearest integer? Of course I can add 0.5 to my value and cast afterwards but that's definitely ugly.
If you're happy to use SVN Trunk, then you might want to take a look at the trunc and round family of functions here: http://svn.boost.org/svn/boost/trunk/libs/math/doc/sf_and_dist/html/math_too... Cheers, John.
If you're happy to use SVN Trunk, then you might want to take a look at the trunc and round family of functions here: http://svn.boost.org/svn/boost/trunk/libs/math/doc/sf_and_dist/html/math_too...
Thanks John. From your answer I read that it doesn't seem to be possible to tell numeric_cast to return the nearest integer, right? So I'd have to round the floating point type to the nearest integer with iround and catch rounding errors instead of the exceptions numeric_cast throws? That's fine with me. Kind regards, Rainer
Rainer Thaden wrote:
If you're happy to use SVN Trunk, then you might want to take a look at the trunc and round family of functions here: http://svn.boost.org/svn/boost/trunk/libs/math/doc/sf_and_dist/html/math_too...
Thanks John. From your answer I read that it doesn't seem to be possible to tell numeric_cast to return the nearest integer, right?
That I don't know, but you'd have to customise it for sure, where as these dedicated rounding functions are intended to do just what they say out of the box :-)
So I'd have to round the floating point type to the nearest integer with iround and catch rounding errors instead of the exceptions numeric_cast throws?
Yep. John.
participants (3)
-
Fernando Cacciola
-
John Maddock
-
Rainer Thaden