Simple convert NSString with comma to float or double. - ios

I have a screen where the user can enter some information. It shows a decimalPad. According to the user locale, I know the decimalPadwill show commaor period, or even something else.
Therefore, my database will contain NSStrings stored from the users, although, some of them will have comma, like 5,4, or period, as in 5.4. The problem is that I need to do some math with these values, and I can't find a pattern to convert them.
Lets say the NSStringhas a comma, as in 5,4. I can easily convert that to a floatusing:
NSNumberFormatter *commas = [NSNumberFormatter new];
commas.numberStyle = NSNumberFormatterDecimalStyle;
NSLocale *commaLocale = [[NSLocale alloc] initWithLocaleIdentifier: #"br_PT"];
commas.locale = commaLocale;
NSString *string = #"5,4";
float testFloat = [[commas numberFromString:string] floatValue];
I correctly get the result 5.4, and can go on with my math calculations. But for instance, if the number was saved by an US user, the NSString would be 5.4, and I wouldn't get the right result using this code. Even if I get user current locale, it doesn't help me, since the user will get values stored all around.
Anyway, I'm a little confused with this. How could I simply create a pattern to deal with this?
I don't want to work with the string, as in stringByReplacingOccurences..., anyway, at least if I can avoid that.

If you want to use the value as a number, you should store the value as a number in your database. NSNumber is a perfect object for that and with your method you can get correct value. When you show the value again to the user you should convert the NSNumber again with NSNumberFormatter. Everything else will be a workaround and have negative impact. Even with stringByReplacingOccurences... you have the risk that somebody uses thousand-dots or commas...

Related

Substring specific integer from string

I have google some related questions, but unfortunately didn't find answer.
I have string like 2016-07-22, i need to get an integer 07, evaluate it to 7 and save.
Of course, this is date, therefore it will change every time, so i cant suppose that year always will be 2016. I need to get string after 5th symbol up to 8th.
Is there any easy way to achieve that? Thanks.
If it's always that section of the string, you can use NSMakeRange(5, 2) and substringWithRange to pick out the month.
After you have "07", conversion is just a case of asking the string for its integerValue.
The "save" part depends entirely on where you want to save it.
Here is just one way (I can think of at least 3 other ways):
NSString *str = #"2016-07-22";
NSArray *elements = [str componentsSeparatedByString:#"-"];
NSAssert([elements count] == 3, #"Ahhh!");
NSInteger month = [elements[1] integerValue];

C4 creating time stamp

I just started saving sceenshots of my current application. Instead of giving the screenshots names beforehand I'd like to use the current date+ time (something unique) as the filename.
I found a method timeIntervalSince1970 in objective C but it doesn't seem to exist in C4. So is there some other function that would return the current date?
timeIntervalSince1970 is a class method of NSDate. If you want to get the current time every screenshot you can use as a unique identifier you can do something like this.
NSString * s = [NSString stringWithFormat:#"awesomeshot%#.jpg", [NSDate date]];
C4Log(#"%#",s );
If you really want to use timeIntervalSince1970 you can check out this discussion: How to convert NSDate into unix timestamp iphone sdk?

Getting Max Date from NSArray, KVC

I've got an array of NSDates and I'd like to grab the largest NSDate from the array. While i could always sort them and grab the first/last, is there a way to do this with KeyValueCoding or some other quick one liner kind of way? I know that I could use something like valueForKeyPath#"#max.date" if the objects had a date property, but what if the objects are dates themselves??
thanks
You can use,
NSDate *maxDate = [dateArray valueForKeyPath:#"#max.self"];
This will give you the largest date from array. You dont have to sort the array before doing this.
From the documentation,
The #max operator compares the values of the property specified by the
key path to the right of the operator and returns the maximum value
found. The maximum value is determined using the compare: method of
the objects at the specified key path. The compared property objects
must support comparison with each other. If the value of the right
side of the key path is nil, it is ignored.
Note that #max will do compare: and then will find out the max value.
Agree with #SeanDanzeiser. To be more specific, here's a ~70 byte one-liner:
// if dateArray is the array of dates ...
NSDate *maxDate = [[dateArray sortedArrayUsingSelector:#selector(compare:)] lastObject];

Whether a blank string should be localized in ios

I have a label which will show the text which I have added using the below code
m_label = [[[NSString stringWithFormat:#"%d",retValue]stringByAppendingString:#" "]stringByAppendingString:NSLocalizedString(#"DAYS",nil)];
So here the text will be displayed in this format: 10(space)days.
I have localised the "days" string,I want to know whether we should localise a space or blank string,
Regards
Ranjit
I think this depends on the languages you are targeting, in the end.
I don't see any particular risks with the expression "10 days", in almost any language I know the number of days would be separated from the word "days" by a space. Of course, I don't know all the languages in the world.
Just an opinion.
Why not simply:
m_label = [NSString stringWithFormat:#"%d %#",
retValue, NSLocalizedString(#"DAYS",nil)];
If the need arises, you can localize the format string. That way, you will not only get flexibility on whitespace, but also e.g., on ordering: putting "DAYS" before their count.

NSLocale is mostly empty - where are the attributes?

I really just want to know whether the user has set the iPhone to 12 hour mode for time display.
The NSLocale class seemed to be describing (in vague unspecific terms without any examples or apparently useful methods) what I was after.
So I have created some NSLocale objects like so:
NSLocale *systemLocaleApparently = [NSLocale systemLocale];
NSLocale *currentLocaleWithLotsOfGoodies = [NSLocale autoupdatingCurrentLocale];
When I inspect these objects using the debugger or NSLog(), the best I can get is something along these lines:
<CFLocale 0x1278e0 [0x382084f8]>{type = system, identifier = ''}
The current locale has an ID string in it, but nothing else.
From the documentation, I can lookup values from the locale, and one of these is an NSCalendar object. So I get that back and have a look at it, and it tells me it is "gregorian".
All of which is apparently of use to somebody... but what I would really like is a nice big dictionary of attributes showing all of the actual system properties, mainly so that my NSDateFormatters don't keep blowing up when a user chooses 12 hour format even though I have forced the formatters to use en_US_POSIX locale and a fixed setDate format.
(I'm sure NSCalendarDate never used to have these problems...)
Hopefully I am missing something blatantly (and probably embarrassingly) obvious, but perhaps someone kind would share it with me. Please :)
Here is one way to tell if the user has set their time format to a 12- or 24-hour format:
NSDateFormatter* formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setTimeStyle:NSDateFormatterMediumStyle];
// Look for H (24-hour format) vs. h (12-hour format) in the date format.
NSString* dateFormat = [formatter dateFormat];
BOOL using24HourClock = [dateFormat rangeOfString:#"h"].location == NSNotFound;

Resources