aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes related to arithmetic operations on datatype. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "related to arithmetic operations on datatype." Watch "related to arithmetic operations on datatype." New topic
Author

related to arithmetic operations on datatype.

Shubhada Nandarshi
Ranch Hand

Joined: Jun 10, 2005
Posts: 59
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?


Shubhada
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18896
    
  40

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 ]

Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Praveen Babu
Ranch Hand

Joined: Jul 30, 2006
Posts: 138
why do you think the output should be 0.48 ?
Petrus Pelser
Ranch Hand

Joined: Feb 20, 2006
Posts: 132
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

Joined: Feb 02, 2006
Posts: 2023
Can float and double value represent decimal number exactly?
Shubhada Nandarshi
Ranch Hand

Joined: Jun 10, 2005
Posts: 59
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

Joined: Jun 10, 2005
Posts: 59
Please can anybody will explain me?
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2367
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: related to arithmetic operations on datatype.