Data types int and float are the same size (32 bits), so why the codes below doen't return 0:
public class testImpl{
public static void main(String[] args){
int i = 1234567890;
float f = i;
System.out.println(i - (int)f);
}
}
Primitive assignment
Moderator: admin
Online
-
- Site Admin
- Posts: 10034
- Joined: Fri Sep 10, 2010 9:26 pm
- Contact:
Re: Primitive assignment
Float has the same size in terms of bits but it uses those bits differently from int. Basically, int uses all its bits to store the exact number while a float uses some bits to store most significant bits of the value and rest of the bits to store the exponent. That is why float loses the lower order digits and so, when you covert it back to int, you will get zeros in those positions. For example, when you covert int 1234567890 to float and then back to int, you may get 1234560000.
See this for exact details: https://introcs.cs.princeton.edu/java/91float/
See this for exact details: https://introcs.cs.princeton.edu/java/91float/
If you like our products and services, please help us by posting your review here.
-
- Posts: 2
- Joined: Mon Oct 28, 2019 7:59 pm
- Contact:
Re: Primitive assignment
Thank you very much !! That was very helpful
Who is online
Users browsing this forum: admin, Bing [Bot] and 17 guests