File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

related to arithmetic operations on datatype.

 
Shubhada Nandarshi
Ranch Hand
Posts: 59
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi friends go through following code:

class test{
public static void main(String agr[]){

float f=Float.parseFloat(agr[0]);
int i=(int)f;

System.out.println("whole no is "+i);
System.out.println("subtraction is "+(f-i));

}
}

generates output when i give no 25.48(or any other float) as
whole no is 25
subtraction is 0.47999954

where the o/ should be:
whole no is 25
subtraction is 0.48

why so?
 
Henry Wong
author
Marshal
Pie
Posts: 20833
75
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Take a look at point #21 in the JavaRanch Beginner's FAQ. It discusses floating point accuracy issues -- and have links if more information is needed.

Henry
[ September 18, 2006: Message edited by: Henry Wong ]
 
Praveen Babu
Ranch Hand
Posts: 138
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
why do you think the output should be 0.48 ?
 
Petrus Pelser
Ranch Hand
Posts: 132
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Shubhada Nandarshi:

int i=(int)f;

System.out.println("whole no is "+i);
System.out.println("subtraction is "+(f-i));



f is truncated when cast to int.
with the subtraction, i is promoted to float and the result is a float.
 
wise owen
Ranch Hand
Posts: 2023
 
Shubhada Nandarshi
Ranch Hand
Posts: 59
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks for reply.
I have one more doubt..how we can convert float or double updo some decided significant digits? e.g. if we want that, answere should be printed upto 4 significant digits only ,then how to do this?
 
Shubhada Nandarshi
Ranch Hand
Posts: 59
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please can anybody will explain me?
 
Keith Lynn
Ranch Hand
Posts: 2399
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can use the DecimalFormat class in the java.text package.

If you need accuracy in decimal numbers, you can use the BigDecimal class in the java.math package.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic