How to get float value that is less then 1 without the higher part

Started by
8 comments, last by BaneTrapper 9 years, 11 months ago

Hello.

I am kinda rusty in language so il just make example code;

I need this


float number = 1.332;
float newNumber = RemoveBigNumber(number);
//newNumber = 0.332;

what is the std function for such a method? i cant find it in

http://www.cplusplus.com/reference/cmath/

Advertisement

Look at it from a different angle instead: how do you obtain the integer part so that you can subtract it from the original number? You can cast the float to an integer, or using the floor function, for example.

Just do something like this


float RemoveIntegerPart(float n)
{
    return n - (int)n;
}

float RemoveWholePart (float N) {
    return N - (int)N;
}

ph34r.png can't delete it.

ph34r.png

modf returns the fractional and integer part of a floating point number.

If you do it with subtraction then remember to check that it gives you the answer you want for negative numbers.

With c++11:

float number = 1.332;

float truncatedNumber = trunc(number);

float wantedNumber = number - truncatedNumber;

Hello to all my stalkers.

float mantissa(float x) {
  return x - std::floor(x);
}

I can't think of any circumstances where you want the answer to be outside of [0,1), so I wouldn't use truncation. Casting to int has even worse problems, since you also have to worry about values larger than what an int can represent.


I can't think of any circumstances where you want the answer to be outside of [0,1), so I wouldn't use truncation.

True -- if negative numbers don't matter, floor would be preferred instead of trunc.

Hello to all my stalkers.

modf returns the fractional and integer part of a floating point number.

If you do it with subtraction then remember to check that it gives you the answer you want for negative numbers.

This is the solution i ended up using.

Thank you on help and i kinda forgot i made this topic mellow.png .

This topic is closed to new replies.

Advertisement