Replace comma with dot when getting floatvalue of NSString - objective-c

I want the users to be able to input values above 0 for a money amount in my application. So 0,0 or any representation of zero will be unacceptable but 0,1 will be accepted, for example.
In order to do this, I was planning to get the float value of NSString and compare it to 0.0 but this does not work since our decimal numbers need to be seperated with comma, always (due to a business requirement). If the commas were dots, then the comparison does the job.
What's the most decent way to replace commas with dots in my amount texts?
PS: The user is limited to enter only numbers and just one comma, for the decimal part.
And actually I was wondering if this is sthg that could be done with number formatters or so...
Thx in advance

You could just use stringByReplacingOccurrencesOfString
NSString *newString = [ammount stringByReplacingOccurrencesOfString:#"," withString:#"."];

You can use the NSString+JavaAPI category, and then do:
NSString* newString = [myString replace: #"," withString: #"."];
Of course, this may not help if the user happens to enter something like 1,000,00.

Here's a neat way to use NSScanner:
NSScanner *scanner = [NSScanner localizedScannerWithString:theInputString];
float result;
[scanner scanFloat:&result];

Apple recommend to use an NSScanner.
this is the code I use :
NSScanner *scanner;
NSLocale *local =[NSLocale currentLocale ];
[scanner setLocale:local];
float result;
scanner = [NSScanner localizedScannerWithString:<YOUR NSString>];
[scanner scanFloat:&result];

Related

Are regexes the right way to extract digits from a ticket number in an NSString?

I would like to programmatically receive a JIRA ticket number, like #"ART-235", and obtain the bare digits / number, #"235".
A question I asked about using regular expressions turned up Regular expressions in an Objective-C Cocoa application with a link to https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSRegularExpression_Class/Reference/Reference.html, and it looks indeed like I can have a regular expression such as \D*?(\d+) and retrieve the value via a regular expression.
However, I wanted to check in and ask if there is a less bletcherous way to do this, or is this an example of why Objective-C is called a bit archaic? The second link gives what looks like everything I need, but it smells a little funny. For the objective stated above, do I want to use regular expressions, or is there a more nicely idiomatic way to perform this sort of string manipulation?
Sounds like -componentsSeparatedByString: would do what you need.
Getting pieces of a fixed, known, format that doesn't use paired delimiters or nesting is exactly the kind of thing that regexes are made to do. I don't see a thing wrong with using one here.
To address your question as written (about "iteration"), however, you might want to look at NSScanner, which does move through the characters of a string by "character class", allowing you to evaluate them as you go.
NSString * ticket = #"ART-235";
NSScanner * scanner = [NSScanner scannerWithString:ticket];
[scanner scanUpToCharactersFromSet:[NSCharacterSet decimalDigitCharacterSet]
intoString:nil];
// As an integer
NSInteger ticketNumber;
[scanner scanInteger:&ticketNumber];
// Or as a string
NSString * ticketNumber;
[scanner scanCharactersFromSet:[NSCharacterSet decimalDigitCharacterSet]
intoString:&ticketNumber];
Like other answers have already said: that simple case can be solved using componentsSeparatedByString:#"-".
That said, your original question is how to enumerate individual characters.
Not all characters are of the same size, some languages combine more than one character into a new language. When enumerating such a string you most likely want to get the resulting of that composition, not the individual pieces. In Objective-C you can enumerate these composed characters like this:
NSString *myString = #"Hello Strings!";
[myString enumerateSubstringsInRange:NSMakeRange(0, myString.length)
options:NSStringEnumerationByComposedCharacterSequences
usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
// Do something with the composed character
NSLog(#"%#", substring);
}];
The example above will log each character one by one.
I made a simple method for you that does the trick, provided that the
ticket identifiers will always be in a "string-number" format !
-(int) numberFromJiraTicket:(NSString*)ticketId
{
//Get number as string
NSString *number = [[ticketId componentsSeparatedByString:#"-"] lastObject];
//Return the INT representation of the number
return [number intValue];
}

NSData to NSString returns Null

I have searched. But still couldnt get it.
I'm converting NSdata to NSString.
When I do [data description];
it returns me <00000000 31323334 35363738>
Yes, Im receiving my string #"12345678".
How do I convert it to NSString appropriately?
I tried
NSString *b = [NSString stringWithUTF8String:[data bytes]];
NSString *a = [[NSString alloc] initWithBytes:[data bytes] length:[data length] encoding:NSUTF8StringEncoding];
Both returns me null.
Any idea?
Thanks
Hi all,
Thanks for all suggestion.
It appears to be constant whereby theres a null character infront always.
So whenever I receive something, i just remove the first <00000000>, then its working fine already
This happens if the encoding is incorrect.
Try using ASCII to test out. ASCII almost certainly work to retrive somekind of string. If it's only numbers it will probably work.
NSString *a = [[NSString alloc] initWithBytes:[data bytes] length:[data length] encoding:NSASCIIStringEncoding];
Most common except UTF-8 enconding is:
NSASCIIStringEncoding
NSUnicodeStringEncoding
NSISOLatin1StringEncoding
NSISOLatin2StringEncoding
NSSymbolStringEncoding
try them out and see if they work.
I'm converting NSdata to NSString. When I do [data description]; it
returns me <00000000 31323334 35363738> Yes, Im receiving my string
#"12345678".
No -- you aren't receiving that string. You are receiving a byte sequence that starts with a bunch of 0x00 values and is followed by a series of bytes that happen to correspond to the ASCII sequence "12345678".
I.e. you have raw data and are trying to convert it to a constrained type, but can't because the constrained type cannot represent the raw data.
You could try using the "lossy conversion" APIs on NSString, but that might not work and would be fragile anyway.
Best bet?
Only convert the bytes in the NSData that actually represent the string to an instance of NSString. That can be done with -initWithBytes:length:encoding:; you'll need to do the calculations to find the correct offset and length.
This may be because the first bytes of your data is 00. The character 0 is the end of string character. When creating a string from ASCII (from an array of chars or an array of bytes as you are doing), when the character 0 is encountered at the beginning, it produces an empty string.
I would however expect it to return an instance of NSString with 0 characters, and not null.

to know the character in a object-c nsstring object

I have an NSString *str and I want to know if the 2nd character is equal to a. How can I do this? I'm new to objective c.
Use this:
[str characterAtIndex:1]
But I always encourage you to check documentation first!
You could also use:
[[str substringWithRange:NSMakeRange(1,1)] isEqualToString:#"a"];
Admittedly, this only becomes handy when you have longer strings for which you're searching.

How to Turn Number into a String with Format?

Say I have a number, double, or NSNumber, 3.333333
I want that to turn that into #"3.3"
How would I do so?
Can I do NSString stringWithFormat? But what's the format?
NSString *str = [NSString stringWithFormat:#"%.1f", yourDouble];
or for NSNumber:
NSString *str = [NSString stringWithFormat:#"%.1f", [yourNSNumber doubleValue]];
0.0f means the amount of digits before and after the decimal. So #Wevah's answer would be correct, but keeping that in mind will save you time in the future.
%f stands for a float variable which I am sure you understand. What you would need to display this is a float variable because it contains a decimal. Like people have stated before, you will need to use %.1f
The % just tells the compiler that a special character is coming up.
The f tells the compiler that it is a float variable.
The .1 tells the compiler how many decimal places your float variable is to have. If you would want to have 6 decimal places, then you would us %.6f
Yes, you will want to use string with format.
Say you have a UILabel, then you will want to say
theLabel'sName.text = [NSString stringWithFormat:#"%.1f", ((float)int1 / int2)];
You need the (float) to tell the compiler that whatever int1 / int2 is, is a float variable.
If your NSNumber instance is called myNumber then do
[myNumber stringValue];

NSString stringWithFormat problem

I have such a problem:
double calcValue;
NSString *buf = [NSString stringWithFormat:#"%14f", myCalculator.calcValue];
buf = "7.142857";
istead of
buf = "7.1428571428571423";
I tried to format it in such ways: #"%f".
But when I tried #"%14.9f" 9 signs after comma displayed.
Whats the problem? And how can I solve it? Thanx!
Unless I'm misunderstanding, the correct format would be #"%.14f.
What you did, #"%14f" says you want up to 14 digits, before the decimal, but you didn't specify digits after.
I'm not sure why, but stringWithFormat: doesn't seem to format doubles properly. You might try this approach:
double calcValue=7.1428571428571423;
NSString *buf=[[NSNumber numberWithDouble:calcValue] stringValue];
which will set buf to #"7.142857142857142".
For tighter control over number of digits, you could use a NSNumberFormatter.