2

Can someone help a rookie? If i have a number 4.561 that is derived from an equation, how can i ONLY display the .561 and ignore the 4?

Thanks in advance. I am new to programming and this is part of an assignment. Any help would be greatly appreciated. I'm coding in c++.

jbsu32
  • 1,036
  • 1
  • 11
  • 31
Nick
  • 21
  • 2

2 Answers2

1

Not sure if this is what you need but do check this out.

float f = 4.561;
f = f-(long)f;
cout << "Value of f is : " << f << endl;
active92
  • 644
  • 12
  • 24
1

I would feel much better with using floor from math.h:

f = 4.561
if (f>=0) f=f-floor(f);
 else     f=f-ceil(f);
// here f = 0.561

for these reasons:

  1. As you do not have control over casting to integral type (f-long(f)) at least I do not know if it is clearly defined as a standard it is using integer part or rounding. Not to mention custom types implementation.

  2. what if your floating value holds bigger number then your integral type can hold? I know there are not that many mantissa bits for fractional part for bigger numbers but you did not specify which floating data-type you are using if 32/64/80/128/256 bits or more so hard to say and if the integer part is bigger then your integral data-type used to cut off the non fractional part then you would be in trouble with f-long(f).

PS.

The if statement could be avoided with masking in and out the sign bit before and after the operation. For example on standard 32bit float it looks like this:

float f=4.561;         // input value
DWORD *dw=(DWORD*)(&f); // pointer to f as integer type to access bits
DWORD m;               // sign storage
m=(*dw)&0x80000000;    // store sign bit to m
(*dw)&= 0x7FFFFFFF;    // f=fabs(f)
f-=floor(f);
(*dw)|=m;              // restore original sign from m
// here f = 0.561   

If you do not have DWORD use any unsigned 32 bit integer instead

Spektre
  • 49,595
  • 11
  • 110
  • 380