cancel
Showing results for 
Search instead for 
Did you mean: 

Problem with floating point numbers

Amey-Mogare
Contributor
0 Kudos

Hi Experts,

I am accepting two float values thru a method :- amount and tenure.

Now wat i want to do is

target = amount / ( tenure * 12 );

but result target is not what it supposed to be. For example:-

if amount = Rs. 15 00 000.0 and tenure = 3 yrs, target amount should be 5 00 000. but it is coming 41666 sumthing.

How should I code this?

Pls help,

regards,

Amey

Accepted Solutions (1)

Accepted Solutions (1)

Former Member
0 Kudos

Hi,

I am accepting two float values thru a method :- amount and tenure.

Now wat i want to do is

target = amount / ( tenure * 12 );

but result target is not what it supposed to be. For example:-

if amount = Rs. 15 00 000.0 and tenure = 3 yrs, target amount should be 5 00 000. but it is coming 41666 sumthing.

How should I code this?

I dont see any error in calculation,

15 00 000.0 / 36 is perfecctly 41666 sumthing

how can you expect this to be 5 00 000?

If you want that change your calculation from

target = amount / tenure ;

Regards

Ayyapparaj

Amey-Mogare
Contributor
0 Kudos

Oh !!! thats rite.... Thank u for pointing it out !!!

formula is same:- target = Amt / ( tenure * 12);

i just want to know that is above safe way to calculate targetAmt??

If i want to use BigDecimal then hw do i go abt it..??

I have changed all data types to double ie Amt, targetAmt and tenure are double now...

regards,

Amey

Former Member
0 Kudos

Hi,

Try as follows



double target;
		double amount = 1500000.0;
		double tenure = 3;
		
		BigDecimal bigTenure = new BigDecimal(tenure);
		BigDecimal bigAmount = new BigDecimal(amount);
		BigDecimal duration = new BigDecimal(12);
		
		BigDecimal t = bigTenure.multiply(duration );
		target = ( bigAmount.divide(t,5,6)).doubleValue();
		System.out.println(target);

Regards

Ayyapparaj

Amey-Mogare
Contributor
0 Kudos

Thanks a lot Ayyapparaj,

It worked like a dream !!!!

Thank you so much...

regards,

Amey

Answers (2)

Answers (2)

Former Member
0 Kudos

Hi,

Always use java.math.BigDecimal class for any kind arithematic operations requires precision.

~kranthi

Amey-Mogare
Contributor
0 Kudos

Thanks alot for quick replies.

Can you please give me sample code for my case? Its very very urgent:-

float targetAmt, amount;

int tenure;

and formula is targetAmt = amount / ( tenure * 12 );

thanks and regards,

Amey

Edited by: Amey Mogare on May 20, 2008 6:21 AM

Former Member
0 Kudos

Hi.

The problem is that "12" is an integer.

(float)/(float)*(int) => (float)/(int) => (int)

Cast your constant to a float or double or even better, use a static variable of type float...

target = amount / ( tenure * 12f );

or

(private static float MONTH_PER_YEAR = 12; )

Regards, Mikael