-4

I am trying to compare two amounts. My problem is that the other amount is a decimal whereas the other one is a Double, I am using the method 'CompareTo()' to compare the amounts and it does not allow the double. I do not want to change the Double amount as it is used in may different places and it could break other peoples code. Is there a way whereby I could convert the Double amount to a Decimal?

Please help

  Double maxSumInsured;
   ProfidaDecimal  totalClaimCost;

   if(totalClaimCost.compareTo(maxSumInsured) > 0){
    //some code here
   }
  • yes, you can convert it to decimal (Integer, BigInt) but you will lose precision. Try the valueOf() method of the Integer object on the Double and checkout the result. Use a sandbox project to observer the behavior :) of the conversions; Do your own research - you'll learn valuable stuff – hovanessyan Jun 05 '13 at 11:54
  • 2
    What *exactly* do you mean by "a Decimal" here? It would really help if you'd show some sample code... – Jon Skeet Jun 05 '13 at 11:54
  • Double maxSumInsured; ProfidaDecimal totalClaimCost; totalClaimCost.compareTo(maxSumInsured) > 0 – TamaraNakani Jun 05 '13 at 12:38
  • You shouldn't be holding money in a double in the first place. This is the real problem. You must always use a decimal type for money. – user207421 Jun 06 '13 at 00:40

3 Answers3

1

If you're dealing with primary types, you don't need to use any compare method to test them for equality. Just cast your int to double :

(double)yourDecimal == yourDouble

If they're boxing types (i.e. Integer and Double instead of int and double), you can still use Equals :

((Double)yourDecimal).Equals(yourDouble)

Or, if you want to use compareTo in order to see which one is greater:

((Double)yourDecimal).compareTo(yourDouble) >0 
// or <0 or ==0 depending on what you're looking for

This SO answer sums about everything you need to know about casting/boxing.

EDIT : Based on OP comment, this should work :

Double maxSumInsured;
maxSumInsured = 0.0; // or anything storable as a double
if(((Double)totalClaimCost).compareTo(maxSumInsured) > 0){
   // ...
}
Community
  • 1
  • 1
xlecoustillier
  • 15,863
  • 14
  • 60
  • 82
1

For converting you can use BigDecimal.valueOf(arg0) and pass this value as argument to 'CompareTo' method

michal
  • 1,801
  • 1
  • 13
  • 11
1

Try Following:

Double d = 5.25;
Integer i = d.intValue(); // i becomes 5
Sumit Singh
  • 24,095
  • 8
  • 74
  • 100