NSNumberFormatter for converting to currencies - objective-c

I need to create a NSFormatter that takes integer values, and sends them to formatted currencies, but the catch is it must add K, and M for thousands and millions. E.G:
130000 -> $130k
12000 -> $12k
10000000 ->$10M
It has to be a datatype NSNumberFormatter since I'll be using it to set a property which takes parameter NSNumberFormatter (I'm formatting the axis labels of a graph).

NSByteCountFormatter can help:
int number = 100000;
NSString *binaryFormatted = [NSByteCountFormatter stringFromByteCount:number countStyle:NSByteCountFormatterCountStyleDecimal];
NSLog(#"binaryFormatted: %#", binaryFormatted);
NSString *digits = [binaryFormatted substringToIndex:binaryFormatted.length-3];
NSString *units = [binaryFormatted substringWithRange:NSMakeRange(binaryFormatted.length-2, 1)];
NSString *currencyFormatted = [NSString stringWithFormat:#"$%#%#", digits, units];
NSLog(#"currencyFormatted: %#", currencyFormatted);
NSLog output
binaryFormatted: 100 KB
currencyFormatted: $100K

Related

Objective-C: Separate number right/left of decimal

I am trying to separate the left and right numbers from a float so I can turn each into a string. So for example, 5.11, I need to be able to turn 5 into a string, and 11 into another string.
// from float: 5.11
NSString * leftNumber = #"5";
NSString * rightNumber = #"11";
From this, I can turn 5.11 into 5' 11".
One way:
Use stringWithFormat to convert to string "5.11".
Use componentsSeparatedByString to seperate into an array of "5" and "11".
Combine with stringWithFormat.
You could use NSString stringWithFormat and math functions for that:
float n = 5.11;
NSString * leftNumber = [NSString stringWithFormat:#"%0.0f", truncf(n)];
NSString * rightNumber = [[NSString stringWithFormat:#"%0.2f", fmodf(n, 1.0)] substringFromIndex:2];
NSLog(#"'%#' '%#'", leftNumber, rightNumber);
However, this is not ideal, especially for representing lengths in customary units, because 0.11 ft is not 11 inches. You would be better off representing the length as an integer in the smallest units that you support (say, for example, 1/16-th of an inch) and then convert it to the actual length for display purposes. In this representation 5 ft 11 in would be 5*12*16 + 11*16 = 1136.
You could use a number formatter as such
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = NSNumberFormatterDecimalStyle;
formatter.decimalSeparator = #"'";
formatter.positiveSuffix = #"\"";
formatter.alwaysShowsDecimalSeparator = true;
NSString *numberString = [formatter stringFromNumber:#(5.11)];
// Output : 5'11"

How to get a CGFloat from a NSString?

In my current app, I have an equation that typically solves to a pretty long amount of decimal numbers, i.e: 0.12345 or .123 . But the way that I need this to work is to only show say 1 or 2 decimal numbers, so that would essentially produce 0.12 or 0.1 based on the values I mentioned.
In order to do this, I have done the following: Taken my CGFloat to a NSString:
CGFloat eX1 = 0.12345
NSLog(#" eX1 = %f", eX1); //This of course , prints out 0.12345
NSNumberFormatter *XFormatter = [[NSNumberFormatter alloc] init];
Xformatter.numberStyle=NSNumberFormatterDecimalStyle;
Xformatter.maximumFractionDigits=1;
NSString *eX1F = [formatter stringFromNumber:#(eX1)];
NSLog (#"eX1F = %#",eX1F); //This prints out 0.1
But my problem is that I need to keep working with this as a CGFloat after it has been formatted, I have tried taken the string back to a number by doing: numberFromString but the problem is that only works with a NSNumber.
What can I do to format my CGFloat and keep working with it as a CGFloat and not a NSString or NSNumber?
Update I have tried:
float backToFloat = [myNumber floatValue];
but the result is number unformatted : 0.10000 I need those extra 0s out
To convert NSString to a CGFloat you can use floatValue:
CGFloat *eX1rounded = [eX1F floatValue];
But you can round eX1 to eX1rounded directly without using a number formatter,
for example:
CFGloat *eX1rounded = roundf(eX1F * 10.0f)/10.0f;
In any case, you should keep in mind that numbers like 0.1 cannot be represented
exactly as a binary floating point number.
Use stringWithFormat: to round and convert to a string for display purposes:
NSString* str = [NSString stringWithFormat:#"%0.2f", eX1];
You can do the same thing in NSLog, the %0.2f says you want 2 decimal places.
NSLog(#" eX1 =%0.2f", eX1); // this prints "0.12"

Convert back localized NSString number (> 4 digits) to integer

I used the localizedStringWithFormat: method on NSString class to convert a seven digit integer number to an NSString somewhere in my code and need to convert it back to an integer now.
As my App is localized for different regions with different separators after three digits (e.g. '.' in the U.S. and ',' in Germany), what's the best way to convert a localized NSString integer value to an integer?
I tried integerValue on my string as follows but it didn't work:
// Somewhere in code:
int num = 1049000;
NSString *myLocalizedNumString = [NSString localizedStringWithFormat:#"%d", num];
// myLocalizedNumString (U.S.): '1,049,000'
// myLocalizedNumString (Germany): '1.049.000'
// Somewhere else where I have a reference to my string but none to the num:
int restoredNum = [myLocalizedNumString integerValue];
// restoredNum isn't 1049000 (it's 0, the initial value)
What would be a good working way of doing it?
Despite its name NSNumberFormatter converts both ways, it is also a string parser. Using the method numberFromString after setting the number formatter’s numberStyle property to NSNumberFormatterDecimalStyle solves your problem.
The code might look as follows:
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = NSNumberFormatterDecimalStyle;
NSInteger restoredNum = [[formatter numberFromString:myLocalizedNumString] integerValue];

NSString intValue deforming actual number

I was making a basic method that takes a Flickr image URL and returns the image's ID.
I'm passing the method the NSString #"http://farm6.staticflickr.com/5183/5629026092_c6762a118f".
The goal is to return the int: 5629026092, which is in the image's URL and is the image's ID.
Here is my method:
-(int)getImageIDFromFlickrURL:(NSString *)imageURL{
NSArray *objectsInURLArray = [imageURL componentsSeparatedByString:#"/"];
NSString *lastObjectInFlickrArray = [objectsInURLArray lastObject];
NSArray *dirtyFlickrIdArray = [lastObjectInFlickrArray componentsSeparatedByString:#"_"];
NSString *flickIDString = [dirtyFlickrIdArray objectAtIndex:0];
NSLog(#"flickr id string: %#",flickIDString);
int flickrID = [flickIDString intValue];
NSLog(#"id: %i",flickrID);
return flickrID;
}
The output in the console is:
2012-05-26 13:30:25.771 TestApp[1744:f803] flickr id string: 5629026092
2012-05-26 13:30:25.773 TestApp[1744:f803] id: 2147483647
Why is calling intValue deforming the actual number?
Use long long instead, your number is greater than int can handle (max being 2147483647 as you can see in your second log)
Your value is too big to represent in 32 bits. The biggest value you can store in a signed 32 bit integer (int) is 2147483647. For unsigned ints, it's 4294967295. You need to convert to a long long integer to represent a number as big as 5629026092.
You'll probably need to create a number formatter for that. I'm no expert on number formatters, and always have to dig out the documentation to figure out how to use them.
I just tried it, and this code works:
NSString *numberString = #"5629026092";
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
NSNumber *number = [formatter numberFromString: numberString];
long long value = [number longLongValue];
NSLog(#"%# = %qi", numberString, value);
[formatter release];
You could also convert the string to a C string and use scanf, come to think of it.
Easy ^^: INT_MAX Maximum value for a variable of type int. 2147483647
I found this to be a convenient way to do it:
NSString *flickIDString = [dirtyFlickrIdArray objectAtIndex:0]; // read some huge number into a string
// read into a NSNumber object or a long long variable. you choose
NSNumber *flickIDNumber = flickIDString.longLongValue;
long long flickIDLong = flickIDString.longLongValue;

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.