Archive for July, 2010

h1

Why use Big Decimal in java

July 11, 2010

When we work with decimals in certain financial related calculations, we see that certain numbers get rounded off incorrectly even though they are stored in double. Below is the example:

public static void main(String o[])
{
double d =3.14159265358979353d;
System.out.println(d);
}

Output is :

3.1415926535897936

It makes sense to have the value as 3.1415926535897935 but not the one that is printed. The reason is double cannot store the right precision for floating point numbers and if you need to store the precision correctly, you need to use Big Decimal. A very good article of using big decimal can be found here

h1

Java Titbits – Filtering files

July 8, 2010

We would have encountered scenarios where we would want to filter certain files within a directory. The traditional method is to get all the files and run through that list and select those that you need. But java  does provide a fileNamefilter class or a fileFilter class that you can use while listing all the files within a directory. (And this has been in jdk since version 1.0 .. something that i didnt know.)

An example to filter all jpeg files in a directory C:\pictures

File myDir = new File(“C:/pictures”);

File[] contents = myDir.listFiles(new FileNameFilter() {

public boolean accept(File directory, String fileName) {

return (fileName.endswith(“jpeg”));

}

} );

You can also use FileFilter if the accept method needs to use any attributes of file object.