ios - Floatting points issue -


i have taken 2 uitextfields & 1 label result of float value inserted in textfields. code have done. here issue starts when takes textfields value in float, getting changed.

- (ibaction)btncalculateamountselected:(id)sender {     nslog(@"[_txtfield1.text floatvalue] is:--> %f ----- [_txtfield2.text floatvalue] is:--> %f",[_txtfield1.text floatvalue],[_txtfield2.text floatvalue]);      float result = [_txtfield1.text floatvalue] - [_txtfield2.text floatvalue];     nslog(@"actual result is:--> %f",result);      float truncatedfloat = truncf(result * 100) / 100.0;     nslog(@"truncatedfloat is:--> %f",truncatedfloat);      _lblresult.text = [nsstring stringwithformat:@"%f", truncatedfloat];     nslog(@"_lblresult.text is:--> %@",_lblresult.text); } 

enter image description here

output is:-

[_txtfield1.text floatvalue] is:--> 1234.123413 ----- [_txtfield2.text floatvalue] is:--> 1234.111084 actual result is:--> 0.012329 truncatedfloat is:--> 0.010000 _lblresult.text is:--> 0.010000 

so 2 responses:

1) floats have limited precision - if want more precision use doubles not floats.

2) if issue dealing currency, dollars , cents, keep values cents, , when displayed cents amount modulo 100 , dollars cents/100 - never odd values if this.


Comments

Popular posts from this blog

java - Jmockit String final length method mocking Issue -

asp.net - Razor Page Hosted on IIS 6 Fails Every Morning -

c++ - wxwidget compiling on windows command prompt -