Paula Atiya
Paula Atiya

Reputation: 33

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"

Upvotes: 3

Views: 194

Answers (5)

mazhar islam
mazhar islam

Reputation: 5619

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.

Upvotes: 6

alexeykuzmin0
alexeykuzmin0

Reputation: 6440

You can cast the float to int, using one of the options below:

var1 = (int)x;
var1 = static_cast<int>(x);
var1 = int(x);

All these options are identical. Also, you can use implicit conversion, but it can cause compile warnings or errors depending on your compiler settings:

var1 = x;

After this conversion you will need to calculate the fractional part:

var2 = x - var1;

Please note that direct conversion to int truncates the fractional part, I mean,

(int)(12.505) == 12
(int)(12.499) == 12
(int)(-12.55) == -12
(int)(-12.49) == -12

If you need some other ways of rounding the number, use ceil(), floor() or round(). These functions are located in header file in std namespace.

Upvotes: 1

Validus Oculus
Validus Oculus

Reputation: 2701

Just use auto truncate functionality.

float f = 12.93;

int b   = f;      // 12
float p = f - b   // 0.93

Upvotes: 0

Peter
Peter

Reputation: 36597

There are various ways.

For one way, look up the function modf() in the standard header <math.h>

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409176

It's very simple if you know that when you convert a floating point value to an integer, it simply truncates the floating point value. So you could simply do

var1 = x;  // Assign 12 to var1
var2 = x - var1;  // Assigns 12.505 - 12 to var2

Upvotes: 7

Related Questions