Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Convert double to int in C?

Tags:

double a; a = 3669.0; int b; b = a; 

I am getting 3668 in b, instead of 3669.

How do I fix This problem? And if have 3559.8 like that also I want like 3559 not 3560.

like image 560
ratty Avatar asked Oct 05 '11 06:10

ratty


People also ask

How do you convert a double to an int?

round() method converts the double to an integer by rounding off the number to the nearest integer. For example – 10.6 will be converted to 11 using Math. round() method and 1ill be converted to 10 using typecasting or Double. intValue() method.

Can you go from double to int?

We can convert double to int in java using typecasting. To convert double data type into int, we need to perform typecasting. Typecasting in java is performed through typecast operator (datatype).

Can we convert int to double in C?

The %d format specifier expects an int argument, but you're passing a double . Using the wrong format specifier invokes undefined behavior. To print a double , use %f .

How do I convert double to int in C++?

Method 1: double final = (int(exam1) + int(exam2) + int(exam3)) / 3; Method 2: int final = int((exam1 + exam2 + exam3) / 3);


2 Answers

I suspect you don't actually have that problem - I suspect you've really got:

double a = callSomeFunction(); // Examine a in the debugger or via logging, and decide it's 3669.0  // Now cast int b = (int) a; // Now a is 3668 

What makes me say that is that although it's true that many decimal values cannot be stored exactly in float or double, that doesn't hold for integers of this kind of magnitude. They can very easily be exactly represented in binary floating point form. (Very large integers can't always be exactly represented, but we're not dealing with a very large integer here.)

I strongly suspect that your double value is actually slightly less than 3669.0, but it's being displayed to you as 3669.0 by whatever diagnostic device you're using. The conversion to an integer value just performs truncation, not rounding - hence the issue.

Assuming your double type is an IEEE-754 64-bit type, the largest value which is less than 3669.0 is exactly

3668.99999999999954525264911353588104248046875 

So if you're using any diagnostic approach where that value would be shown as 3669.0, then it's quite possible (probable, I'd say) that this is what's happening.

like image 152
Jon Skeet Avatar answered Oct 09 '22 04:10

Jon Skeet


main() {     double a;     a=3669.0;     int b;     b=a;     printf("b is %d",b);    } 

output is :b is 3669

when you write b=a; then its automatically converted in int

see on-line compiler result :  

http://ideone.com/60T5b


This is called Implicit Type Conversion Read more here https://www.geeksforgeeks.org/implicit-type-conversion-in-c-with-examples/

like image 37
Jeegar Patel Avatar answered Oct 09 '22 04:10

Jeegar Patel