• Post Reply Bookmark Topic Watch Topic
  • New Topic

Unable to perform division  RSS feed

 
Ranch Hand
Posts: 39
Chrome Java Notepad
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
I am very new to java as well as coderanch

I am trying to develop something using netbeans but I am struck at a point where compiler point out an error .



When I divide with 100 instead of 105.5 it works fine, I am unable to get what is happening?

Please help
 
author & internet detective
Marshal
Posts: 37518
554
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can you post the error? I'm guessing it is about the type or casting?
 
Sheriff
Posts: 11496
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you are using a literal value of 105.5, then it's a double by default. You can't do that if the variable you are assigning the result to is a float (single precision 32-bit floating point) because the presence of a double value in the expression will force a widening conversion to a double-precision 64-bit floating point value. You need to either change the declared type of the variable to double or use a float literal, 105.5f, instead.

See http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html for more info.
 
Junilu Lacar
Sheriff
Posts: 11496
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The reason it works with the literal value 100 is because a numeric literal like that without a decimal point is treated as an int. An int is smaller than a float, so a widening conversion from int to float is not going to be a problem.
 
Marshal
Posts: 56610
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

Don't use floats unless some other API specifically requires them. If you are going to use floating‑point arithmetic, always use doubles for better precision.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!