iTunes Search API, finding Free prices - objective-c

When searching the iTunes store, I've hit a little problem. I'm trying to change the text of my label to "FREE" when the price is 0.00, as opposed to displaying the price. The problem is, my comparison of the two NSDecimalNumbers fails. Here's where I am currently at.
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterCurrencyStyle];
[formatter setCurrencyCode:self.searchResult.currency];
NSString *price = [formatter stringFromNumber:self.searchResult.price];
NSDecimalNumber *free = [[NSDecimalNumber alloc] initWithFloat:0.00f];
NSLog(#"Price:%#",price);
NSLog(#"Free:%#",free);
NSLog(#"self.searchResult.price: %#", self.searchResult.price);
if (self.searchResult.price == free) {
NSString *freeText = [NSString stringWithFormat:#"FREE"];
self.priceLabel.text = freeText;
}
else {
self.priceLabel.text = price;
}
NSLog(#"priceLabel:%#", self.priceLabel.text);
What's really weird is that the Console even says that both free and del.searchResult.price are the same:
2012-11-24 20:01:16.178 StoreSearch[1987:c07] Price:$0.00
2012-11-24 20:01:16.178 StoreSearch[1987:c07] Free:0
2012-11-24 20:01:16.178 StoreSearch[1987:c07] self.searchResult.price: 0
2012-11-24 20:01:16.179 StoreSearch[1987:c07] priceLabel:$0.00
I'm a little confused by this to be frank. Any help would be appreciated. If you could explain why this has happened so that I can learn not to do it again, then I'd be even more grateful!
Regards,
Mike

you got NSNumber and another NSNumber (NSDecimalNumber) and you do a pointer equal check you either need need to call isEqual or compare the primitive float values
== with objects doesnt compare the value but the object pointer (the memory address)
if(searchResult.price.floatValue == free.floatValue)
note that a float is inprecise and generally should not be used for any calculation or comparison. It is ok in this case though

Related

Large (but representable) integers get parsed as doubles by NSNumberFormatter

I've been using the following method to parse NSString's into NSNumber's:
// (a category method on NSString)
-(NSNumber*) tryParseAsNumber {
NSNumberFormatter* formatter = [NSNumberFormatter new];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
return [formatter numberFromString:self];
}
And I had tests verifying that this was working correctly:
test(#"".tryParseAsNumber == nil);
...
test([(#NSUIntegerMax).description.tryParseAsNumber isEqual:#NSUIntegerMax]);
...
The max-value test started failing when I switched to testing on an iPhone 6, probably because NSUInteger is now 64 bits instead of 32 bits. The value returned by the formatter is now the double 1.844674407370955e+19 instead of the uint64_t 18446744073709551615.
Is there a built-in method that succeeds exactly for all int64s and unsigned int64s, or do I have to implement one myself?
+ [NSNumber numberWithLongLong:]
+ [NSNumber numberWithUnsignedLongLong:]
Have you tried these?
EDIT
I'm not at all certain what it is you'd ultimately do with your instances of NSNumber, but consider that NSDecimalNumber seems to do exactly what you want:
NSDecimalNumber *decNum = [NSDecimalNumber decimalNumberWithString:#"18446744073709551615"];
NSLog(#"%#", decNum);
which yields:
2014-09-21 15:11:25.472 Test[1138:812724] 18446744073709551615
Here's another thing to consider: NSDecimalNumber "is a" NSNumber, as it's a subclass of the latter. So it would appear that, whatever you can do with NSNumber, you can do with NSDecimalNumber.
trudyscousin's answer allowed me to figure it out.
NSDecimalNumber decimalNumberWithString: is capable of parsing with full precision, but it lets some bad inputs by (e.g. "88ffhih" gets parsed as 88). On the other hand, NSNumberFormatter numberFromString: always detects bad inputs but loses precision. They have opposite weaknesses.
So... just do both. For example, here's a method that should parse representable NSUIntegers but nothing else:
+(NSNumber*) parseAsNSUIntegerElseNil:(NSString*)decimalText {
// NSNumberFormatter.numberFromString is good at noticing bad inputs, but loses precision for large values
// NSDecimalNumber.decimalNumberWithString has perfect precision, but lets bad inputs through sometimes (e.g. "88ffhih" -> 88)
// We use both to get both accuracy and detection of bad inputs
NSNumberFormatter* formatter = [NSNumberFormatter new];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
if ([formatter numberFromString:decimalText] == nil) {
return nil;
}
NSNumber* value = [NSDecimalNumber decimalNumberWithString:decimalText];
// Discard values not representable by NSUInteger
if (![value isEqual:#(value.unsignedIntegerValue)]) {
return nil;
}
return value;
}

NSNumber stringValue different from NSNumber value

I'm having problems with converting NSNumber to string and string to NSNumber.
Here's a sample problem:
NSString *stringValue = #"9.2";
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
NSLog(#"stringvalue:%#",[[formatter numberFromString: stringValue] stringValue]);
Output will be:
stringvalue:9.199999999999999
I need to retrieve the original value, where, in the example should be 9.2.
On the contrary, when the original string is 9.4 the output is still 9.4.
Do you have any idea how to retrieve the original string value without NSNumber doing anything about it?
You are discovering that floating point numbers can't always be represented exactly. There are numerous posts about such issues.
If you need to get back to the original string, then keep the original string as your data and only convert to a number when you need to perform a calculation.
You may want to look into NSDecimalNumber. This may better fit your needs.
NSString *numStr = #"9.2";
NSDecimalNumber *decNum = [NSDecimalNumber decimalNumberWithString:numStr];
NSString *newStr = [decNum stringValue];
NSLog(#"decNum = %#, newStr = %#", decNum, newStr);
This gives 9.2 for both values.

Dynamicaly rounding numbers in Objective-C

I know that there are many different questions about this sort of topic on SO already, but I couldn't find a way to tailor them all to my specific needs.
What I have is a floating point number that gets sent to me through the network that I need to convert and graph out to the screen. The numbers can range from 5.2, 285.159, 294729172.258, -10734.112, etc. What I would like to do is get the value used to round from one digit below the most significant digit.
Example:
5.2 = 5
285.159 = 300
294729172.258 = 300000000
-10734.112 = -11000
Any advice that can be used to help guide me would be greatly appreciated.
Here's my solution:
int roundMostSignificant(float input)
{
NSNumber *number = [NSNumber numberWithFloat:input];
static NSNumberFormatter *formatter = nil;
if (!formatter)
{
formatter = [NSNumberFormatter new];
[formatter setMinimumSignificantDigits:1];
[formatter setMaximumSignificantDigits:1];
[formatter setUsesSignificantDigits:YES];
}
return [[formatter numberFromString:[formatter stringFromNumber:number]] intValue];
}
Yes, this uses objects, but I think that this will be your best bet in the long run, as it handles rounding, parsing, etc. for you.
There is a NSDecimalNumber and NSDecimalNumberHandler classes which does just that. You can define to which precision and to which direction the numbers should be rounded.
Simple example might be:
NSDecimalNumber *dn = [NSDecimalNumber decimalNumberWithMatnissa:294729172258 exponent:-3 isNegative:NO];
NSDecimalNumberHandler *dnh = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundPlain scale:-6 raiseOnExactness:NO raiseOnOverflow:NO raiseOnUnderflow:NO raiseOnDivideByZero:YES];
NSDecimalNumber *rounded = [dn decimalNumberByRoundingAccordingToBehavior:dnh];
This would probably work for your biggest number.

parsing string into different kind of number string

I have a string called realEstateWorth with a value of $12,000,000.
I need this same string to remain a string but for any number (such as the one above) to be displayed as $12 MILLION or $6 MILLION. The point is it needs the words "MILLION" to come after the number.
I know there is nsNumberFormatter that can convert strings into numbers and vice versa but can it do what I need?
If anyone has any ideas or suggestions, it would be much appreciated.
Thank you!
So as I see it, you have two problems:
You have a string representation of something that's actually a number
You (potentially) have a number that you want formatted as a string
So, problem #1:
To convert a string into a number, you use an NSNumberFormatter. You've got a pretty simple case:
NSNumberFormatter *f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterCurrencyStyle];
NSNumber *n = [f numberFromString:#"$12,000,000"];
// n is 12000000
That was easy! Now problem #2:
This is trickier, because you want a mixed spell-out style. You could consider using an NSNumberFormatter again, but it's not quite right:
[f setNumberStyle:NSNumberFormatterSpellOutStyle];
NSString *s = [f stringFromNumber:n];
// s is "twelve million"
So, we're closer. At this point, you could perhaps maybe do something like:
NSInteger numberOfMillions = [n integerValue] / 1000000;
if (numberOfMillions > 0) {
NSNumber *millions = [NSNumber numberWithInteger:numberOfMillions];
NSString *numberOfMillionsString = [f stringFromNumber:millions]; // "twelve"
[f setNumberStyle:NSNumberFormatterCurrencyStyle];
NSString *formattedMillions = [f stringFromNumber:millions]; // "$12.00"
if ([s hasPrefix:numberOfMillionsString]) {
// replace "twelve" with "$12.00"
s = [s stringByReplacingCharactersInRange:NSMakeRange(0, [numberOfMillionsString length]) withString:formattedMillions];
// if this all works, s should be "$12.00 million"
// you can use the -setMaximumFractionDigits: method on NSNumberFormatter to fiddle with the ".00" bit
}
}
However
I don't know how well this would work in anything other than english. CAVEAT IMPLEMENTOR
Worst case scenario, you could implement a category on NSString to implement the behaviour you want.
In the method that you would do in that category you could take an NSNumberFormatter to bring that string to a number and by doing some modulo operation you could define if you need the word Million, or Billion, etc. and put back a string with the modulo for Million or other way you need it to be.
That way you could just call that method on your NSString like this :
NSString *humanReadable = [realEstateWorth myCustomMethodFromMyCategory];
And also.
NSString are immutable, so you can't change it unless you assign a new one to your variable.
I'd recommend storing this value as an NSNumber or a float. Then you could have a method to generate an NSString to display it like:
- (NSString*)numberToCurrencyString:(float)num
{
NSString *postfix = #"";
if (num > 1000000000)
{
num = num / 1000000000;
postfix = #" Billion";
}
else if (num > 1000000)
{
num = num / 1000000;
postfix = #" Million";
}
NSString *currencyString = [NSString stringWithFormat:#"%.0f%#", num, postfix];
return currencyString;
}
Note: Your question states that your input needs to remain a string. That's fine. So you'd need to 1.) first parse the number out of the string and 2.) then reconvert it to a string from a number. I've shown how to do step 2 of this process.

How to format this NSString correctly?

I want to format a string that can look like that:
0.0580 which means 5.8 ct
0.1580 which means 15.8 ct
1.1580 which means 1.15 €
So the string can be anything in x.xxxx format. Now I started formating it but I am new to objective-c and iOS.
First I want to remove the last character because the last number does not really matter and I don't want to round numbers.
NSString *responseString = [responseData
substringWithRange:NSMakeRange(1,
[responseData length]-2)];
This gives me x.xxx so far. Any idea how to proceed and what code to use? Are there any libraries on that?
Take a look at the NSNumberFormatter class. It should do what you need. Something like this:
NSNumberFormatter *numFormatter = [[NSNumberFormatter alloc] init];
NSNumber *myNumber = [NSNumber numberWithDouble:[#"0.158" doubleValue]];
[numFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
NSString *formattedValue = [numFormatter stringFromNumber:myNumber];
[numFormatter release];
Also look at NSNumberFormatterStyle and NSNumberFormatterBehavior to control the format.
Once you have your number in the form x.xxx, you could do something like:
float floatValue = [#"0.158" floatValue]; // Get your string as a number.
floatValue *= 100; // Turn '0.158' into '1.58'
Does this answer your question? I'm not quite sure that it does, so update your question and I will try to assist you better.