vpiotr / decimal_for_cpp

Decimal data type for C++
273 stars 68 forks source link

how to get an int/double from dec type ? #48

Closed omerbrandis closed 3 years ago

omerbrandis commented 3 years ago

Hi

Can you please share the method to extract/convert to basic types?

for example : int myInt; dec<2> myDec("1"); myInt = myDec ; currently this returns a "cannot convert error". i've also tried dec<2,null_round_policy>... to no avail.

furthermore, what I actually need right now is to perform a conversion on a "temporary"(implicitly defined) variable , for example :
int result = (decA - DecB) / DecC; (in this case I precheck that the result of this calculation is in fact an integer)

Please advise, Omer.

omerbrandis commented 3 years ago

I've tried using DEC_NAMESPACE::round but got "error: invalid static_cast from type ‘DEC_NAMESPACE::decimal<8>’ to type ‘DEC_NAMESPACE::int64 {aka long int}’ int64 intPart = static_cast(val1);

omerbrandis commented 3 years ago

managed to compile : std::istringstream(DEC_NAMESPACE::toString (( dec calculation )) >> int;

but this feels like a problematic hack and not the intended api. :-)

Omer.

vpiotr commented 3 years ago

If you want to convert to integer with rounding, just use getAsInteger(). If you want to extract only integer part ignoring fractional part use unpack. See https://github.com/vpiotr/decimal_for_cpp/blob/master/tests/decimalTest.ipp for more examples.