-1

I´ve read a lot of posts about this but all of them were to limit the number digits to show them(NSString) .In my case I have:

I compare two double values(wich are the "same"), each of them got from different mathematical operations. For example: (4.800000 and 4.800000)

double result1=4.800000, result2=4.800000

//compare the results:

if(result1==result2){
    msg.text=@"well done!!";        
}else if(result1>result2){
    msg.text=@"continue your work";    
}

"I´m working with money (4,80€)"

In the msg label i get "continue your work" message, not the "well done". I don´t even know if the comparison is done in a correct way.

I think that the best idea would be to limit 4.800000 to 4.80 in order to delete small values and get a exact comparison.(how could i do this?) I DONT WANT to limit the number to two digits just to PRINT the solution, I want to WORK with that number.

hakre
  • 193,403
  • 52
  • 435
  • 836
iopy
  • 5
  • 1
  • 4

3 Answers3

0

You can do something like this:

double a = 2.55000, b = 2.55002;
if(fabs(a-b)<1e-3) {
    // code here, a == b
} else {
   // code here, a != b
}
AndrewShmig
  • 4,843
  • 6
  • 39
  • 68
  • Cool idea but: if a =2.440000 and b=2.42000 appears the code a==b – iopy Feb 01 '13 at 18:24
  • @asierReisa, show me your ObjC code where a==b and a=2.44 and b=2.42 – AndrewShmig Feb 01 '13 at 18:33
  • Here is the code: if((dineroObjetivo-sumadinerodejado)<1e-3) { mensajeResultado.text=[[NSString alloc]initWithFormat:@"MUY BIEN!! resta: %f",dineroObjetivo-sumadinerodejado]; } else { //juego completado pero dinero de sobra mensajeResultado.text=[[NSString alloc]initWithFormat:@"Te sobra dinero: %f, intenta usar los cambios que tienes",(sumadinerodejado-dineroObjetivo)]; } – iopy Feb 01 '13 at 18:41
  • But nothing...if i get 4.200 & 4.199 its OK but if i get a higher value as 4.200 & 4.350 -->error – iopy Feb 01 '13 at 18:43
  • in your code you are not using abs\fabs, so its clear why its not working correctly – AndrewShmig Feb 01 '13 at 18:44
  • sorry, i have changed but i get the same problem – iopy Feb 01 '13 at 18:46
  • 1
    YEah! there we go!! i changed abs for fabs and the aproblemas are gone! Anddrew I really appreciate your patience and help, Its an important work for the university that i have to finish tomorrow! Thank you!! – iopy Feb 01 '13 at 18:49
0

use floor(<#double#>) to round down OR just subtract them and floor the result.

Yariv Nissim
  • 13,273
  • 1
  • 38
  • 44
0

For a nice answer to this problem see:
https://stackoverflow.com/a/10335601/474896

Which could be summarized as a simple as:

if (fabs(x-y) < FLT_EPSILON) {/* ... */}

However since you you're working with money values you should check out NSDecimalNumber.

Or as Marcus Zarra puts it:

"If you are dealing with currency at all, then you should be using NSDecimalNumber.".

Community
  • 1
  • 1
Joris Kluivers
  • 11,894
  • 2
  • 48
  • 47