This week's book giveaway is in the Cloud/Virtualizaton forum.We're giving away four copies of Mesos in Action and have Roger Ignazio on-line!See this thread for details.
Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!

# Issue with the Parse Float

Jyothish Divakar
Greenhorn
Posts: 10
Hi,

I am using the following code to find a difference between two floating integers in string format and returns a string as well.

public String floatDifference(String value1, String value2) {

float diffValue = 0.0f;
String retVal = "";
diffValue = Float.parseFloat(value1)
- Float.parseFloat(value2);
retVal = Float.toString(diffValue);
return retVal;
}

This method is giving me a precision of 4 digits in the result. For instance I passed "2510.00" and "856.32" and it returns "1653.6799" but when I pass "2510.00" and "856.52" and it returns "1653.48". I am using J2SE version 1.4.

Can anyone help in investigating on why is this precision get changed for different inputs?

Regards,
Jyothish

Ulf Dittmer
Rancher
Posts: 42967
73
You might want to read this on floating point accuracy.

Vilmantas Baranauskas
Ranch Hand
Posts: 89
Not sure if you are dealing with money but somewhere I've seen a very good example of how to deal with money in OO-way.

The idea is to have special Money class with methods add(Money), subtract(Money). Then you write myPocket.add(new Money(...)).

Internally you may store money depending on requirements. One option would be to store amount*100.

In addition, you can introduce easily currency support later if needed.

Ulf Dittmer
Rancher
Posts: 42967
73
Indeed, float and double should not be used for monetary calculations - use the BigDecimal class instead.

Peter Chase
Ranch Hand
Posts: 1970
The original poster doesn't say that the calculations involve money. The two-decimal-place requirement does suggest money, though.

Using floating-point (float or double) for money calculations is a seriously bad idea. Don't do it!

Jyothish Divakar
Greenhorn
Posts: 10
Hi all,

Thanks for your speedy response. i used the NumberFormat and got the solution for the digit issue. but really i wanted to know why is this different behaviour to different sets of data of same kind.

Thanks,
Jyothish

Ernest Friedman-Hill
author and iconoclast
Marshal
Posts: 24211
35
Go read the link Ulf gave you above. The short answer is that some real numbers simply can't be represented exactly in floating point.
[ April 28, 2008: Message edited by: Ernest Friedman-Hill ]