Java Mistake 1 - Using float and double for monetary or financial calculation
ava is considered very safe programming language compared to C and C++ as it doesn't have free() and malloc() to directly do memory allocation and deallocation, You don't need to worry of array overrun in Java as they are bounded and there is pointer arithmetic in Java. Still there are some sharp edges in Java programming language which you need to be aware of while writing enterprise application. Many of us make subtle mistake in Java which looks correct in first place but turn out to be buggy when looked carefully. In this series of java articles I will be sharing some of common Java mistake programmers make while programming application in Java. As I have said earlier every day we learn new things but we forget something equally important. This again highlight importance of code review and following best practices in Java. In this part we will discuss why double and float should not be used in monetary or financial calculation where exact result of calculation is expected.
Using double and float for exact calculation
This is one of common mistake Java programmer make until they are familiar with BigDecimal class. When we learn Java programming we have been told that use float and double to represent decimal numbers its not been told that result of floating point number is not exact, which makes them unsuitable for any financial calculation which requires exact result and not approximation. float and double are designed for engineering and scientific calculation and many times doesn't produce exact result also result of floating point calculation may vary from JVM to JVM. Look at below example of BigDecimal and double primitive which is used to represent money value, its quite clear that floating point calculation may not be exact and one should use BigDecimal for financial calculations.
Read full article from Java Mistake 1 - Using float and double for monetary or financial calculation
No comments:
Post a Comment