Dynamically format a float in a NSString for iOS - 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];

Related

NSDictionary with float value return wrong conversion

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);

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];
}

Unusual stringWithFormat: argument

I apologize if this is a noob question.
I have been following this tutorial about mapkit and I stumbled on this line of code
NSString *json = [NSString stringWithFormat:formatString,
centerLocation.latitude,
centerLocation.longitude,
0.5 * METERS_PER_MILE];
The reason this is unusual at least to me is that it is missing the nsstring that has the %# flags in it. The tutorial claims that we are adding the latitude and longitude information into the json.
But when I print out formatString and json, the output is identical.
I have never seen nsstrings used in this way before. Is there a hidden variable that is getting set?
Can someone explain to me how this nsstring object (named json) contains those 4 arguments?
Someplace else in the code, formatString must be defined something like this:
NSString *formatString = #"latitude=%f, longitude=%f, %f = half the number of meters in a mile";
Make sure your test looks like this:
NSLog(#"the format is %# and the json is %#", formatString, json);
They shouldn't look the same. The only way they would look the same is if format string doesn't refer to any format specifiers, like this:
NSString *formatString = #"I'm a silly format with no percent format specifiers";
Here's a good intro on the topic from Apple.
That formatString actually contains the %#'s. It might be like this:
NSString *formatString = #"lat: %f | lon: %f | half-meters-per-mile: %f";
NSString *json = [NSString stringWithFormat:formatString,
centerLocation.latitude,
centerLocation.longitude,
0.5 * METERS_PER_MILE];
(note that the substitutions (%f) might not be correct, I'm guessing)
As for how it contains those four arguments, everything after the first one are values that you want added into the string. The first one is a string that says where to put those values.
If you check the tutorial, following line of code is written above what you have posted-
NSString *jsonFile = [[NSBundle mainBundle] pathForResource:#"command" ofType:#"json"];
NSString *formatString = [NSString stringWithContentsOfFile:jsonFile encoding:NSUTF8StringEncoding error:nil];
From here the format string is created, this file will be available in the resources folder of your tutorial.

Convert NSString with factor (e.g. #"3/4") to NSNumber [duplicate]

This question already has answers here:
Convert to Float and Calculate
(3 answers)
What is a fast C or Objective-C math parser? [closed]
(4 answers)
Closed 9 years ago.
I want to convert a string for example
NSString *stringWithNumber = #"3/4"
into a NSNumber.
How is this possible?
You can use an NSEXpression to "calculate" the value. Note that you will have the regular int division problem with "3/4".
NSExpression *expression = [NSExpression expressionWithFormat:#"3.0/4.0"];
NSNumber *result = [expression expressionValueWithObject:nil context:nil];
If you are only working with n/m fractions, and you mean to have a number representing the result of the fraction, you can do something like
NSString *fraction = #"3/4";
NSArray *components = [fraction componentsSeparatedByString:#"/"];
float numerator = [components[0] floatValue];
float denominator = [components[1] floatValue];
NSNumber *result = #(numerator/denominator);
NSLog(#"%#", result); // => 0.75
Of course this can easily break in case of malformed strings, so you may want to check the format before performing the above computation.
NOTE
In case the fractions coming in input have a format compatible with native float division, David's answer is definitely sleeker and less clunky than mine. Although if you have an input like #"3/4", it won't work as expected and you definitely need to do something like I suggested above.
Bottom line, you should specify better your requirements.

NSNumber storing float. Please NO scientific notation?

My code looks like this
NSNumber *inputToNumber = [NSNumber numberWithFloat:[textField.text floatValue]];
the value from the textfield is actually a telephone number. It's stored in NSNumber as an annoying (2.0)78966e+08
How can I just get NSNumber to store it as 0207896608?
I think that the basic idea to store a phone number into a NSNumber is flawed:
how do you discriminate between numbers with or without leading 0 ?
how do you store phone numbers from foreign countries ?
I would use NSString in place of NSNumber.
Just because it's called a number doesn't mean a "telephone number" is a number in the same sense that "5" or "pi" are.
Either you should treat a telephone number as a string, or you should create a TelephoneNumber model class to represent each one.
Consider that there are places in the world where numbers don't have leading 0's and where a number with a leading 0 is not the same as the same number without a leading 0.
05843924 != 5843924
So stop being lazy with that NSNumber hacks and build your own phone-number class.
Scientific notation is used in may computer languages as the default output of very large (or very small) numbers. If you want the number to be output as a decimal, you need to specify the output format (the implementation varies by language.)
Also, julesjacobs is correct. You should not use FLOAT for a phone number as it is subject to binary rounding errors. Using INT or STRING will save you lots of headaches.
If you need to be able to deal with it as numbers maybe you should break it up into its parts, and store each part as an integer.
01112223333
country code 0
area code 111
prefix 222
number 3333
Or you could store the whole thing as a string if you don't need to manipulate it.
Are you storing a phone number in a float? You should consider using an integer or string. Perhaps:
NSNumber *inputToNumber = [NSNumber numberWithInt:[textField.text intValue]];
Hey Guys what do you think of this, It seems to full-fill my purposes. Only UK at the moment so will worry about localization when I get a chance.
I use this to get to store the number
NSNumber *inputToNumber = [NSNumber numberWithLongLong:(long long)[[textField.text stringByReplacingOccurrencesOfString:#" " withString:#""] longLongValue]];
And this method formats my telephone number and takes care of the preceeding 0 mentioned.
-(NSString *)phoneNumberString:(NSNumber *)phoneNumber {
//Add a zero because NSNumber won't save a preceeding zero
NSString *telephoneString = [[NSString alloc] initWithFormat:#"0%#", [phoneNumber stringValue]];
if (telephoneString.length >= 4) {
NSString *firstPart = [[NSString alloc] initWithString: [telephoneString substringToIndex:4]];
NSString *secondPart = [[NSString alloc] initWithString: [telephoneString substringFromIndex:4]];
//Add the two parts together with a space inbetween
NSString *formattedTelephoneString = [NSString stringWithFormat:#"%# %#", firstPart, secondPart];
//send it back to the cellForRow TableCell Method
[firstPart release];
[secondPart release];
[telephoneString release];
return formattedTelephoneString;
}
else {
return telephoneString;
}
}
Thanks for all the comments. I'm gonna mark the answer as whoever suggested NSString as I fear I will revert to using NSString for this instead of my above workaround.

Resources