Converting NSDecimalNumber to NSString - objective-c

I'm retrieving a key from an object that looks like this:
po obj
{
TypeID = 3;
TypeName = Asset;
}
The key value is being retrieved like this:
NSString *typeId = (NSString*)[obj objectForKey:#"TypeID"];
Rather than typeId being an NSString, it is an NSDecimalNumber. Why is that?
How do I convert it to an NSString?

You need to use the stringWithFormat function:
NSString *typeId = [NSString stringWithFormat:#"%#", [obj objectForKey:#"TypeID"]];
or stringValue:
NSString *typeId = [[obj objectForKey:#"TypeID"] stringValue];

This should work:
NSString *typeId = [[obj objectForKey:#"TypeID"] stringValue];

If you want to get string value, just use "description". It works fine even if returned type is NSDecimalNumber, or NSString, or whatever:
NSString *typeId = [[obj objectForKey:#"TypeID"] description];

Since this is the top search result and I don't see a question for NSDecimalNumber to String in Swift, here it is. This will show the localized decimal separator and all decimal places with a non-zero value.
let string = decimalNumber.description(withLocale: Locale.current)

Use this to convert NSDecimalNumber to NSString:
NSDecimalNumber* dec1;
NSString* str;
str = dec1.stringValue;
Use this to convert NSString to NSDecimalNumber:
NSString* string1 = #"Stack overflow 123";
NSDecimalNumber* dec;
dec = (NSDecimalNumber *)string1;

Related

Simple int to NSString conversion as in Java?

Is there any simple way how to initialize String in Objective-C with int such as in Java:
String myStr = 42 + "";
or I have to do
[NSString stringWithFormat:#"%d", 42];
everytime?
You could also use the NSNumber class for that:
NSNumber *number = [[NSNumber alloc] initWithInteger: val];
NSString *string = [number stringValue];
Perhaps not shorter, but it could be eventually faster.
Also you could create as said a helper method, than you wouldn't have to use more code than with the stringWithFormat: method.
Yes you have to do
[NSString stringWithFormat:#"%d", 42];
for Integer to string conversion.
Using a constant, like 42 in your example, you can write
NSString *myString = #"42";
Using a variable or expression, you can write
[NSString stringWithFormat:#"%d", myValue];

Going crazy with UITextField

I'm literally going crazy whit these six rows of code.
NB: nome and prezzo are 2 textFields
NSString *itemName = (NSString *) [rowVals objectForKey:#"name"];
NSString *itemPrice = (NSString *) [rowVals objectForKey:#"price"];
nome.text = itemName;
nome.userInteractionEnabled = YES;
prezzo.text = itemPrice;
prezzo.userInteractionEnabled = YES;
Don't know why when itemPrice is copied in one of those label, the program go in SIGABRT.
Instead if I try to read the content with an NSLog(#"%#",itemPrice); it return the exact value, so it means that is a valid NSString.
The only solution I found is passing through a NSNumber:
NSNumber *itemPrice = (NSNumber *) [rowVals objectForKey:#"price"];
prezzo.text = [[NSString alloc] initWithFormat:#"%#", itemPrice];
There is another way to use directly the NSString?
Probably the value in the #"price" field is NSNumber, and not an NSString. The NSLog method will still provide a correct result, since %# is used for any NSObject subclass, not just NSString.
How about this:
NSString *itemPrice = [[rowVal objectForKey:#"price"] stringValue];
prezzo.text = itemPrice;
The problem might be the object type returned by [rowVals objectForKey:#"price"]. When you place the (NSString *) cast before the method call, you're telling the compiler what type of object is returned, but not actually converting it into an NSString. The line you use below does convert from NSNumber (or whatever other object) to a string: [[NSString alloc] initWithFormat:#"%#", itemPrice]
You might be storing NSNumber's object in NSDictionary instead of NSString.
There could be 2 ways: one would be to convert NSNumber to NSString while adding it to dictionary or the other way would be to convert NSNumber to NSString while assigning it to "itemName".
you may do the conversion for second option like:
NSString *itemPrice = [[rowVals objectForKey:#"price"]stringValue];

Objective-c integer to string giving random numbers?

I'm busy working on an iPad application and my web service returns pretty simple JSON data. All seems well and I have other methods doing this same conversion without issue however, I have 1 method that returns a random string when doing a integer -> string conversion.
My userdata object below is a NSDictionary created by the SBJSON parser. The value when debugging of [userdata objectForKey:#"UserID"] is 1.
However when I do this
NSString *userId = [NSString stringWithFormat:#"%d", [userdata objectForKey:#"UserID"]];
The value in userId is or appears to be a random number such as 23425234. I also tried the %d in my format but got the same result.
Because it is an object, not an int, you see the address of the object, instead, you can do that:
NSString *userId = [NSString stringWithFormat:#"%#", [userdata objectForKey:#"UserID"]];
^
Try with:
NSString *userId = [NSString stringWithFormat:#"%d", [[userdata objectForKey:#"UserID"] intValue]];
Or:
NSString *userId = [NSString stringWithFormat:#"%#", [userdata objectForKey:#"UserID"]];
object for key is probably NSNumber and not int...

String parsing in Objective-C

When I have pf:/Abc/def/, how can I get the /Abc/def/?
With Python, I can use
string = 'pf:/Abc/def/'
string.split(':')[1]
or even
string[3:]
What's the equivalent function in Objective-C?
NSString *string = [NSString stringWithFormat:#"pf:/Abc/def/"];
NSArray *components = [string componentsSeparatedByString: #":"];
NSString *string2 = (NSString*) [components objectAtIndex:1];
Reference: http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/occ/instm/NSString/componentsSeparatedByString:
componentsSeparatedByString will return an NSArray. You grab the object at a certain index, and type cast it to NSString when storing it into another variable.

How to convert NSNumber to NSString

So I have an NSArray "myArray" with NSNumbers and NSStrings. I need them in another UIView so i go like this:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
DetailViewController *details = [[DetailViewController alloc] initWithNibName:#"DetailView" bundle:nil];
details.subjectText = [[myArray objectAtIndex:indexPath.row] objectForKey:#"subject"];
The subjectText works.
But how can I get the NSNumbers out of it? (I actually need them as strings...)
I would convert a NSString out of a NSNumber like this:
NSString *blah = [NSNumber intValue]. But I don't know how to set it up in the code above...
Try:
NSString *myString = [NSNumber stringValue];
You can do it with:
NSNumber *myNumber = #15;
NSString *myNumberInString = [myNumber stringValue];
//An example of implementation :
// we set the score of one player to a value
[Game getCurrent].scorePlayer1 = [NSNumber numberWithInteger:1];
// We copy the value in a NSNumber
NSNumber *aNumber = [Game getCurrent].scorePlayer1;
// Conversion of the NSNumber aNumber to a String with stringValue
NSString *StringScorePlayer1 = [aNumber stringValue];
or try NSString *string = [NSString stringWithFormat:#"%d", [NSNumber intValue], nil];
The funny thing is that NSNumber converts to string automatically if it becomes a part of a string. I don't think it is documented.
Try these:
NSLog(#"My integer NSNumber:%#",[NSNumber numberWithInt:184]);
NSLog(#"My float NSNumber:%#",[NSNumber numberWithFloat:12.23f]);
NSLog(#"My bool(YES) NSNumber:%#",[NSNumber numberWithBool:YES]);
NSLog(#"My bool(NO) NSNumber:%#",[NSNumber numberWithBool:NO]);
NSString *myStringWithNumbers = [NSString stringWithFormat:#"Int:%#, Float:%# Bool:%#",[NSNumber numberWithInt:132],[NSNumber numberWithFloat:-4.823f],[NSNumber numberWithBool:YES]];
NSLog(#"%#",myStringWithNumbers);
It will print:
My integer NSNumber:184
My float NSNumber:12.23
My bool(YES) NSNumber:1
My bool(NO) NSNumber:0
Int:132, Float:-4.823 Bool:1
Works on both Mac and iOS
This one does not work:
NSString *myNSNumber2 = [NSNumber numberWithFloat:-34512.23f];
In Swift you can do like this
let number : NSNumber = 95
let str : String = number.stringValue
In Swift 3.0
let number:NSNumber = 25
let strValue = String(describing: number as NSNumber)
print("As String => \(strValue)")
We can get the number value in String.