Question:
I want to check if a boost::multiprecision::cpp_dec_float<100> value can be safely converted into a float/double or (u)int8,16,32,... without range problems
Background:
The cpp_dec_float is comming from an CSV import (i can't change that - its not my code) with constant values that "should" always fit (column dependent) into int8, int16, ...,double or float
some sort of:
bool can_be_converted_to_double(const cpp_dec_float<100>& ft)
double converted_to_double(const cpp_dec_float<100>& ft)
bool can_be_converted_to_int8(const cpp_dec_float<100>& ft)
int8_t converted_to_int8(const cpp_dec_float<100>& ft)
bool can_be_converted_to_uint8(const cpp_dec_float<100>& ft)
uint8_t converted_to_uint8(const cpp_dec_float<100>& ft)
its ok to loose precision when converting to float/double but the integral part value should fit
for integers it should not work if fractional part != 0 or the integral part does not fit
i tried to use .extract_signed_long_long and extract_part but that could fail if the values too large and there seem to be no convert_to helper available
how to test if the conversion can work and also do it?
Update
how to check if the fractional part is 0 - this way?
cpp_dec_float_100 value( "123.1" );
cpp_dec_float_100 int_part = value.backend().extract_integer_part();
cpp_dec_float_100 fractional_part = value - int_part;
bool has_fractional_zero = fractional_part.is_zero();
I suppose this would be a good start:
Here's some tests to verify your requirements:
Live On Coliru
Prints
UPDATE
I had kinda missed the requirement to check for fractional parts. In my mind, rounding to integer is "just" precision loss, so nothing to worry about.
To also detect fractional parts, I'd suggest the simplest:
Using implementation details of the backend type might speed it up a little, at the expense of making it less generic/potentially more error-prone.
Extendeding the tests using it (choosing a "noise" value relative to the source value and significant digits of the decimal float type):
Still prints the same output: Live On Coliru