Search code examples
c++castingnumberspoint

float number casting c++


I want to put the number in the left hand side of the float point in a new variable from a float number ex:

int var1;
float var2;
float x=12.505;     // i want the number 12 to put it in "var1" and 0.505 in "var2"

Solution

  • var1 = x; // var1 is 12
    var2 = x - var1; // var2 is 0.505
    

    Run live.

    Note that,

    If the conversion is from a floating-point type to an integer type, the value is truncated (the decimal part is removed). If the result lies outside the range of representable values by the type, the conversion causes undefined behavior.

    Read more about Type conversions.