AlwaysNub - 4 months ago 34

C++ Question

If I have a signed long variable that holds the whole number part of a decimal and another long variable that holds the fraction part, how would I convert that to a float or double type?

The fraction part is scaled to the 9th place.

Example:

signed long h = -5;

long f = 200073490

Result should be -5.20007349

Example 2:

signed long h = 3;

long f = 500100;

Result should be 3.0005001

Edit

Also: looking for a mathematical solution. Converting to string and scanning it back into float/double will not work in my project.

Answer

Since the `long int`

, `h`

, representing the fractional part is scaled by 1000,000,000 you just need to divide it by 1000000000 and correct for the sign in the event the integer portion of the pair is negative. That is you add the scaled fractional part when the base number is positive and subtract the scaled fractional part when the base number is negative. Given that `h`

is the integer portion and `f`

is the fractional portion an expression that combines these to produce a double is:

`double result=h + (1-2*(h < 0)) * f/1000000000.0;`

The expression `(1-2*(h < 0))`

yields a 1 when h is not negative otherwise a -1.