Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C convert floating point to int

I'm using C (not C++).

I need to convert a float number into an int. I do not want to round to the the nearest number, I simply want to eliminate what is after the integer part. Something like

4.9 -> 4.9 -> 4
like image 566
A. O. Avatar asked Jul 13 '14 13:07

A. O.


People also ask

How do I convert a float to an int in C?

The way to get the value is either the lib function int floor(float) or (for roundingup) int ceil(float).

Can we store float into integer variable in C?

So you cannot store a float value in an int object through simple assignment. You can store the bit pattern for a floating-point value in an int object if the int is at least as wide as the float , either by using memcpy or some kind of casting gymnastics (as other answers have shown).

What happens when you convert a float to an int?

Convert a float to an int always results in a data loss. The trunc() function returns the integer part of a number. The floor() function returns the largest integer less than or equal to a number. The ceil() function returns the smallest integer greater than or equal to a number.

Can we convert float to char in C?

gcvt() | Convert float value to string in C This function is used to convert a floating point number to string. Syntax : gcvt (float value, int ndigits, char * buf); float value : It is the float or double value.


Video Answer


2 Answers

my_var = (int)my_var; 

As simple as that. Basically you don't need it if the variable is int.

like image 112
Zach P Avatar answered Oct 04 '22 05:10

Zach P


Use in C

int C = var_in_float; 

They will convert implicit

like image 36
user3161739 Avatar answered Oct 04 '22 05:10

user3161739