# related to arithmetic operations on datatype.

Ranch Hand
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?

Henry Wong
author
Marshal
Posts: 21420
84
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
why do you think the output should be 0.48 ?

Petrus Pelser
Ranch Hand
Posts: 132

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

Ranch Hand
Posts: 59
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?

Ranch Hand
Posts: 59
Please can anybody will explain me?

Keith Lynn
Ranch Hand
Posts: 2409
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.