Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIlabel gives incorrect float value at runtime

I am assigning a float value to a UIlabel and when the limit exceeds its limit to handle, the value changes and shows me incorrect result.I am using autoresize text with a minimum font text value and truncate tail. I am making a calculator.If i want a result for 50000x50000 the the result should be 2500000000.0000 but the label shows something like 2499999548.0000

like image 262
Yieshu Avatar asked May 08 '26 15:05

Yieshu


1 Answers

If you have a read of http://en.wikipedia.org/wiki/Floating_point... you will find that any number larger than about 10,000 needs to be using a 64 bit float instead of a 32 bit float if you want to have four decimal places.

The double data type is a 64 bit float.

Be especially careful of CGFloat because that will be 64 bit on an iPhone 5S and 32 bit on an iPhone 5C and any older iPhone.

A 64 bit float is accurate for numbers in the billions. Anything larger than that and you'll want to start working with the NSDecimalNumber class. This is probably what you should do for a calculator app.

https://developer.apple.com/library/ios/documentation/cocoa/reference/foundation/classes/nsdecimalnumber_class/reference/reference.html

Here's a demonstration of why you shouldn't use float or double when you need accuracy:

float aFloat = 10000.2;
float bFloat = 10000.0;
NSLog(@"%.15f", aFloat - bFloat); // 0.200195312500000

double aDouble = 10000.2;
double bDouble = 10000.0;
NSLog(@"%.15f", aDouble - bDouble); // 0.200000000000728

NSDecimalNumber *a = [NSDecimalNumber decimalNumberWithString:@"10000.2"];
NSDecimalNumber *b = [NSDecimalNumber decimalNumberWithString:@"10000.0"];
NSLog(@"%@", [a decimalNumberBySubtracting:b]); // 0.2

It's even worse with really big numbers:

float aFloat = 10000000000000000000000.2;
float bFloat = 10000000000000000000000.0;
NSLog(@"%.15f", aFloat - bFloat); // 0.000000000000000

double aDouble = 10000000000000000000000.2;
double bDouble = 10000000000000000000000.0;
NSLog(@"%.15f", aDouble - bDouble); // 0.000000000000000

NSDecimalNumber *a = [NSDecimalNumber decimalNumberWithString:@"10000000000000000000000.2"];
NSDecimalNumber *b = [NSDecimalNumber decimalNumberWithString:@"10000000000000000000000.0"];
NSLog(@"%@", [a decimalNumberBySubtracting:b]); // 0.2
like image 114
Abhi Beckert Avatar answered May 11 '26 05:05

Abhi Beckert