Decimal problem in Java
Posted
by
Jerome
on Stack Overflow
See other posts from Stack Overflow
or by Jerome
Published on 2011-01-11T05:07:31Z
Indexed on
2011/01/11
5:54 UTC
Read the original article
Hit count: 251
java
I am experimenting with writing a java class for financial engineering (hobby of mine). The algorithm that I desire to implement is:
100 / 0.05 = 2000
Instead I get:
100 / 0.05 = 2000.9999999999998
I understand the problem to be one with converting from binary numbers to decimals (float --> int). I have looked at the BigDecimal class on the web but have not quite found what I am looking for.
Attached is the program and a class that I wrote:
// DCF class
public class DCF {
double rate;
double principle;
int period;
public DCF(double $rate, double $principle, int $period) {
rate = $rate;
principle = $principle;
period = $period;
}
// returns the console value
public double consol() {
return principle/rate;
}
// to string Method
public String toString() {
return "(" + rate + "," + principle + "," + period + ")";
}
}
Now the actual program:
// consol program
public class DCFmain {
public static void main(String[] args) {
// create new DCF
DCF abacus = new DCF(0.05, 100.05, 5);
System.out.println(abacus);
System.out.println("Console value= " + abacus.consol() );
}
}
Output:
(0.05,100.05,5)
Console value= 2000.9999999999998
Thanks!
© Stack Overflow or respective owner