NSDictionary with float value return wrong conversion - ios

I have NSDictionary with floating values, I am trying to get values like this
[[NSDictionary valueForKey:#"some_value"] floatValue];
but looks like value not rounded correctly.
For example:
I have value in dictionary: #"0.35" but after above conversion returns 0.34999999403953552 float value, #"0.15" converts into 0.15000000596046448 etc.

When you are converting value from string to float, it lost its precision so you have to format it again. Please look at below the question you will get the better idea of that.
Make a float only show two decimal places

Converting Dictionary value to float
NSString *str = [dict objectForKey:#"key"];
CGFloat strFloat = (CGFloat)[str floatValue];

Try this code, It will work for you. Tested!
float myFloatValue= 2345.678990;
NSString* formattedNumber = [NSString stringWithFormat:#"%.02f", myFloatValue];
NSLog(#"Changed Float Value:%#",formattedNumber);

Related

Dynamically format a float in a NSString for iOS

I am having the same issues as here: Dynamically format a float in a NSString.
I have searched my hardest for the answer but everything I do seems to break it.
I have tried the following code:
cell.distanceLabel.text = [NSString stringWithFormat:#"%#km",[item objectForKey:#"distance"]];
the displayed value should only ever have two decimals but for some reason values between 1.00 and 9.99 display with more than two decimals.
Can anyone help me with what I am doing wrong here?
I believe you have to either use:
NSLog(#"THE LOG SCORE : %f", x);
OR you need to convert the float to a string like this:
NSString *myString = [[NSNumber numberWithFloat:myFloat] stringValue];

Assign the value from a text field into an int variable to do some math with other variables and then return it?

The code showing here assigns the value of an variables to the text field I want to do the opposite of that.
_Initial.text = [NSString stringWithFormat:#"%f", init];
The opposite of the code above. Please help
The opposite of that would be getting converting string to float. You can do it with this
init = [_Initial.text floatValue];
You should search for an answer before you ask a question.
NSString *intString = #"123";
NSString *floatString = #"456.789";
int intVal = [intString intValue];
float floatVal = [floatString floatValue];
printf("%i %f\n",intVal,floatVal);

How to avoid rounding off the float value when called from sqlite

I am using the following statement to get a float value from table:
NSNumber *f = [NSNumber numberWithDouble:(double)sqlite3_column_double(statement, 0)];
The value in the database is 23.679999999 but I am getting 23.68. I tried numberWithFloat but i got the same result.
Can anyone tell me how to get the value without rounding off?
NSNumber-wrapped-double is not a suitable data type for storing decimal values when all digits must be preserved exactly. Use NSDecimalNumber instead:
unsigned char *c = sqlite3_column_text(statement, 0);
NSNumber *f = nil;
if (c) {
NSString *numStr = [NSString stringWithUTF8String:c];
f = [NSDecimalNumber decimalNumberWithString:numStr];
}
This should preserve all significant digits available in your text representation, as long as you use the native value. Converting to float or double may result in rounding due to differences in representation.

XCode not using decimal number, only using whole digit

I am trying to multiply three TextField's values which are in numbers. These values can contains decimal places. In multiplication Objective-C does not consider decimal places. For example, if the number was 3.45, it would only multiply by 3 and not with the decimals as well. Might be a basic question but i am stuck and really need help!
Here's the code i'm using so far:
- (IBAction)CalculateSimple:(id)sender {
int sum = [[principal text] intValue] * [[rate text] intValue] * [[loan text] intValue];;
total.text = [NSString stringWithFormat:#"$%d", sum]; }
Use double instead of int:
double sum = [[principal text] doubleValue] *
[[rate text] doubleValue] *
[[loan text] doubleValue];
total.text = [NSString stringWithFormat:#"$%f", sum];
You are using intValue (which returns integer type, thus your calculations are done on integers). You need to use floatValue or doubleValue (depending on your needs).
Also - check int/float/double types, if you don't know them yet.
You transform each of your operands to an intValue. Furthermore your result is also declared as an int variable.
Variables of type int can only store whole numbers.
If you want to work with floating point numbers use an appropriate data type like float or double depending on your desired precision and the size of the value.
Take the documentation on values in Objective-C as a reference.
When you are printing your result you also have to match the placeholder to the data type.
See the String Programming Guide
So with that in mind your method would look like this:
- (IBAction)CalculateSimple:(id)sender {
float sum = [[principal text] floatValue] * [[rate text] floatValue] * [[loan text] floatValue];
total.text = [NSString stringWithFormat:#"$%f", sum];
}

NSNumber to float Value

When I convert NSNumber to float value using 'floatValue', there is a difference in precision. Example, I have a NSNumber 'myNumber' having value 2.3, and if I convert myNumber to float using 'floatValue', its value becomes, 2.29999. But I need exactly 2.30000. There is no problem with number of zeros after 2.3, I need '2.3' instead of '2.9'.
How can I do so?
I had similar situation where I was reading value and assigning it back to float variable again.
My Problem statement:
NSString *value = #"553637.90";
NSNumber *num = #([value floatValue]); // 1. This is the problem. num is set to 553637.875000
NSNumberFormatter *decimalStyleFormatter = [[NSNumberFormatter alloc] init];
[decimalStyleFormatter setMaximumFractionDigits:2];
NSString *resultString = [decimalStyleFormatter stringFromNumber:num]; // 2. string is assigned with rounded value like 553637.88
float originalValue = [resultString floatValue]; // 3. Hence, originalValue turns out to be 553637.88 which wrong.
Following worked for me after changing lines:
NSNumber *num = #([value doubleValue]); // 4. doubleValue preserves value 553637.9
double originalvalue = [resultString doubleValue]; // 5. While reading back, assign to variable of type double, in this case 'originalValue'
I hope this would be helpful. :)
If you need exact precision, don't use float. Use a double if you need better precision. That still won't be exact. You could multiply myNumber by 10, convert to an unsigned int and perform your arithmetic on it, convert back to a float or double and divide by 10 and the end result might be more precise. If none of these are sufficiently precise, you might want to look into an arbitrary precision arithmetic library such as GNU MP Bignum.
I've done the following but it is showing me correctly
NSNumber *num = [NSNumber numberWithFloat:2.3];
float f = [num floatValue];
NSLog(#"%f", f);
You can play with something like this:
float x = 2.3f;
NSNumber *n = [NSNumber numberWithFloat:x];
NSNumberFormatter *fmt = [[NSNumberFormatter alloc] init];
[fmt setPositiveFormat:#"0.#"];
NSString *s = [fmt stringFromNumber:n];
float f = [s floatValue];

Resources