How can i convert a string to float in Objective C without rounding it.?
I tried to convert a string 8.56021285234;
float result=[string floatValue];
giving 8.560213, the rounded value.
How can i avoid this? How i can get the exact value?
How can i convert a string to float in Objective C without rounding it.?
I tried to convert a string 8.56021285234;
float result=[string floatValue];
giving 8.560213, the rounded value.
How can i avoid this? How i can get the exact value?
You can't put more than about 7 digits of precision in a float. You need a type with more precision, like double, see here:
The problem is you're using a float. A float can usually only hold around 7-digits max. A double can hold many more digits. A float is 32-bit while a double is 64-bit therefore giving it "double" the precision. A simple work-around to your problem would be to do:
double result = [string doubleValue];
When logging, make sure to use NSLog(@"%.12f",result);
to show the entire double as %f defaults to only a 6 decimal precision.
Try double instead of float:
NSString *val = @"8.56021285234";
double num = [val doubleValue];
NSLog(@"Number ==> %f",num);
If you want to convert it use
double result = [string doubleValue];
For displaying it use %.10f to specify decimal places:
NSLog(@"%.10f", result);
NSString *value = @"8.44654656565";
double dblValue = [value doubleValue];
NSLog(@"%.10f",dblValue);
the double variable have the all information you need, then you format it as text system can display not the whole digits stored in double variable
The Sabareesh code:
NSString *value = @"8.44654656565";
double dblValue = [value doubleValue];
NSLog(@"%.12f",dblValue);
here dblValue have in memory all digits you want and you can use it as you want
NSLog here can prove you have enough data - simply because NSLog output it
Please try NSDecimal Number instead of [string floatValue];
NSDecimalNumber *price1 = [NSDecimalNumber decimalNumberWithString:@"15.99"];
NSDecimalNumber *price2 = [NSDecimalNumber decimalNumberWithString:@"29.99"];
NSDecimalNumber *coupon = [NSDecimalNumber decimalNumberWithString:@"5.00"];
NSDecimalNumber *discount = [NSDecimalNumber decimalNumberWithString:@".90"];
NSDecimalNumber *numProducts = [NSDecimalNumber decimalNumberWithString:@"2.0"];
NSDecimalNumber *subtotal = [price1 decimalNumberByAdding:price2];
NSDecimalNumber *afterCoupon = [subtotal decimalNumberBySubtracting:coupon];
NSDecimalNumber *afterDiscount = [afterCoupon decimalNumberByMultiplyingBy:discount];
NSDecimalNumber *average = [afterDiscount decimalNumberByDividingBy:numProducts];
NSDecimalNumber *averageSquared = [average decimalNumberByRaisingToPower:2];
NSLog(@"Subtotal: %@", subtotal); // 45.98
NSLog(@"After coupon: %@", afterCoupon); // 40.98
NSLog((@"After discount: %@"), afterDiscount); // 36.882
NSLog(@"Average price per product: %@", average); // 18.441
NSLog(@"Average price squared: %@", averageSquared); // 340.070481