formatting value in a string to have a decimal separator - objective-c

if i have a value stored like:
long long unsigned x=1000000000000;
i'd like to have a
NSString *strx=[...];
so if i use NSLog or bitmapfont for this integer, what is displayed will be:
1,000,000,000,000
do exists this king od formatter?
thanks

NSNumberFormatter is the class to go to. For example:
long num = 1000000000;
NSNumberFormatter *fmt = [[NSNumberFormatter alloc] init];
fmt.positiveFormat = #"#,###";
NSLog(#"%#", [fmt stringFromNumber:[NSNumber numberWithLong:num]]);
prints out 1,000,000,000. There are a lot of predefined styles and further options that can be explored:
NSNumberFormatter reference: http://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSNumberFormatter_Class/Reference/Reference.html
Format patterns: http://unicode.org/reports/tr35/tr35-10.html#Number_Format_Patterns

Related

How to properly display currency iPhone/Objective-C

I am trying to properly display properly formatted currencies from long values. I am using NSNumberFormatter however it seems to be cutting off my decimal places where the cents would go.
For example, if I have a long value of 1203 (cents) I want it to have a fixed point format (like 12.03). Here is what I have done:
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = NSNumberFormatterCurrencyStyle;
formatter.currencyCode = "USD";
formatter.multiplier = [NSNumber numberWithDouble:0.01];
long currencyAmount = 1203;
NSNumber *number = [NSNumber numberWithLongLong:currencyAmount];
[label setText:[formatter stringFromNumber:number]];
I am getting this output $12.00 but I want $12.03
To think of an integer cut-off bug inside of NSNumberFormatter is crazy speculation but have you tried the default multiplier of one and dividing your currency amount after conversion to float by 100 yourself?
EDIT: For this workaround the following post suggests the use of NSDecimalNumber to avoid rounding problems. NSNumberFormatter to format currency not working for floats
I figured out the answer. This will properly format a long/long long value to a currency.
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = NSNumberFormatterCurrencyStyle;
formatter.currencyCode = "USD";
long currencyAmount = 1203;
NSDecimalNumber *wrappedCurrencyAmount = [NSDecimalNumber decimalNumberWithMantissa:currencyAmount exponent:-2 isNegative:NO];
[label setText:[formatter stringFromNumber:wrappedCurrencyAmount]];

objective c - Xcode long int display with formatting

I’m having issues with this when the numbers are large. For example if the number is 3670000000, I want the label to be 3,670,000,000. When the numbers are large it gives me a value of 2,147,483,657. I’m sure it must be a variable length issue. I tried using long long int for numC. Any suggestions would be greatly appreciated. Thanks.
int numC;
NSNumberFormatter *formatter = [NSNumberFormatter new];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
NSString *valuestring= [NSString stringWithFormat:#"%#", [[values objectAtIndex:indexA] objectForKey:#"hits"]];
numC=[valuestring intValue];
NSString *results = [formatter stringFromNumber:[NSNumber numberWithInteger:numC]];
label1.text =results;
The int type cannot hold a value greater than 2,147,483,657. You could use an unsigned int and the maximum value would be 4,294,967,295. Look here for more information. You could try this too to extend the range of the data type:
long long int numC;
//Number formatter and string operations
numC = [valuestring longLongValue];
NSString *results = [formatter stringFromNumber:[NSNumber numberWithLongLong: numC]];
label1.text = results;
Additionally, if none of the values you are retrieving contain a negative value, you could make it an unsigned long long int. In that case, make your code this:
unsigned long long int numC;
//Number formatter and string operations
numC = [valuestring longLongValue];
NSString *results = [formatter stringFromNumber:[NSNumber numberWithUnsignedLongLong: numC]];
label1.text = results;
Also make sure that in this line...
NSString *valuestring= [NSString stringWithFormat:#"%#", [[values objectAtIndex:indexA] objectForKey:#"hits"]];
...the value you are retrieving is a long long int.
Hope this helps!
There is also the C++ class for bigInteger if you really need to do operations with numbers larger than allowed by int. If you don't need to do many operations, store the number as a NSString. Then to work with it just take the end of the string, convert it to an int, do your operations, then put the number back into the string.

Why aren't the decimals printed to the string?

In order to get a string with 2 decimals value I've tried:
[[NSString stringWithFormat:#"%.2f",[[self CurrentValue] doubleValue]]]
this
[self CurrentValue] stringValue]
and this:
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = NSNumberFormatterCurrencyStyle;
NSString *string = [formatter stringFromNumber:[self CurrentValue]];
[formatter release];
But it doesn't work. THe original number is a float = 22, and I always get a string "22", and not "22.00".
Thanks
I ran a few test scenarios and hopefully this can help you get to the bottom of it. The formatter is ideal if you are doing a currency, otherwise string1 is ideal. To work from this example you can set number up - NSNumber * number = [self CurrentValue];
NSNumber * number = [NSNumber numberWithInt:22];
NSString * string1 = [NSString stringWithFormat:#"%.2f",[number doubleValue]];
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = NSNumberFormatterCurrencyStyle;
NSString *string2 = [formatter stringFromNumber:number];
[formatter release];
NSLog(#"string 1 %#\nstring 2 %#\nstring 3 %#", string1, string2, [number stringValue]);
//output
string 1 22.00
string 2 $22.00
string 3 22
// top code with NSNumber * number = [NSNumber numberWithFloat:22];
string 1 22.00
string 2 $22.00
string 3 22
// top code with NSNumber * number = [NSNumber numberWithFloat:22.0];
string 1 22.00
string 2 $22.00
string 3 22
Summary:
The way the number is created is not significant here to the output if it is truly an int (floats with such as 4.20 will work as expected in every case, but every int value 22,22.0,22.000 gets treated the same by all 3 ways of creating a number. So choose the format you like best and implement that.
Seems you have extra [] around. You can try
[NSString stringWithFormat:#"%.2f",[[self CurrentValue] floatValue]]
or
[NSString stringWithFormat:#"%.2lf",[[self CurrentValue] doubleValue]] both are good to go.
It actually much simpler.
You said that "The original number is a float = 22". Now, remember that obj-c runtime class may differ from declared one. And when you instantiate your float variable with actually integer value - it is an integer one at runtime! You should change it to one of the following:float someFloatValue = 22f;float someFloatValue = 22.0;float someFloatValue = (float)22; (not sure about that one thought)
Happy coding...

How to add commas to number every 3 digits in Objective C?

If I have a number int aNum = 2000000 how do I format this so that I can display it as the NSString 2,000,000?
Use NSNumberFormatter.
Specifically:
NSNumberFormatter *formatter = [NSNumberFormatter new];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle]; // this line is important!
NSString *formatted = [formatter stringFromNumber:[NSNumber numberWithInteger:2000000]];
[formatter release];
By default NSNumberFormatter uses the current locale so the grouping separators are set to their correct values by default. The key thing is to remember to set a number style.
Don't do your own number formatting. You will almost certainly not get all the edge cases right or correctly handle all possible locales. Use the NSNumberFormatter for formatting numeric data to a localized string representation.
You would use the NSNumberFormatter instance method -setGroupingSeparator: to set the grouping separator to #"," (or better yet [[NSLocale currentLocale] objectForKey:NSLocaleGroupingSeparator]; thanks #ntesler) and -setGroupingSize: to put a grouping separator every 3 digits.
There's a static method on NSNumberFormatter that does just what you need:
int aNum = 2000000;
NSString *display = [NSNumberFormatter localizedStringFromNumber:#(aNum)
numberStyle:NSNumberFormatterDecimalStyle];
This way is a little more succinct than creating a new NSNumberFormatter if you don't need to do any additional configuration of the formatter.
Even easier:
NSNumber *someNumber = #(1234567890);
NSString *modelNumberString = [NSString localizedStringWithFormat:#"%#", someNumber];
NSLog(#"Number with commas: %#", modelNumberString);
coworker just taught me this today. #amazing
Think some as i will get this post looking for sample.
So if you are working with number make attention on next params:
setNumberStyle:NSNumberFormatterCurrencyStyle // if you are working with currency
It could be also
setNumberStyle:NSNumberFormatterDecimalStyle
All code is For ARC.
If you are working with Integer and need to get result such as 200,000
int value = 200000;
NSNumberFormatter * formatter = [NSNumberFormatter new];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
NSString * newString = [formatter stringFromNumber:[NSNumber numberWithInteger:value]];
If you are working with Float and need to get result such as 200,000.00
float value = 200000;
NSNumberFormatter * formatter = [NSNumberFormatter new];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setMaximumFractionDigits:2]; // Set this if you need 2 digits
NSString * newString = [formatter stringFromNumber:[NSNumber numberWithFloat:value]];
EDIT
To have ability to use different digital separators use NSLocale.
Add to code where NSLocale is specified on Locale Identifier:
[formatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:#"de_DE"]];
or use current local:
[formatter setLocale:[NSLocale currentLocale]];
Swift version
let formatter = NSNumberFormatter()
formatter.numberStyle = .DecimalStyle
formatter.maximumFractionDigits = decimalPlaces
let result = formatter.stringFromNumber(NSNumber(double: 8.0))
By http://ios.eezytutorials.com
An easy solution could be this. My answer is almost same like #Nazir's answer but with a small trick.
double current_balance = 2000000.00;
NSNumberFormatter * formatter = [NSNumberFormatter new];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
//[formatter setNumberStyle:NSNumberFormatterCurrencyStyle]; //if you want for currency with $ sign
[formatter setMinimumFractionDigits:2]; // Set this if you need 2 digits
[formatter setMaximumFractionDigits:2]; // Set this if you need 2 digits
NSString * currency_format = [NSString stringWithFormat:#"%#", [formatter stringFromNumber:[NSNumber numberWithDouble:current_balance]]];
For Swift 4.0
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.minimumFractionDigits = 2
formatter.maximumFractionDigits = 2
let result = formatter.string(from: NSNumber(value: 123456))
For those who need to do it with strings of numbers and not just integers (I.e. Big Numbers) I made the following macro:
#define addCommas(__string) (\
(^NSString *(void){\
NSString *__numberString = __string;\
NSString *__integerPortion = __numberString;\
NSString *__decimalPortion = #"";\
if ([__string containsString:#"."]) {\
__integerPortion = [__numberString componentsSeparatedByString:#"."][0];\
__decimalPortion = st(#".%#", [__numberString componentsSeparatedByString:#"."][1]);\
}\
int __i = (int)__integerPortion.length-3;\
while (__i > 0) {\
__integerPortion = st(#"%#,%#", substringInRange(__integerPortion, 0, __i), substringInRange(__integerPortion, __i, (int)__integerPortion.length));\
__i -= 3;\
}\
__numberString = st(#"%#%#", __integerPortion, __decimalPortion);\
return __numberString;\
})()\
)

Objective-C: How to format string as $ Price

Is their a built-in way of formatting string as $ price, e.g. 12345.45 converted to $12,345.45?
Assuming you are using Cocoa (or just Foundation), you can use NSNumberFormatter and set its style to currency:
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterCurrencyStyle];
... = [formatter stringFromNumber:number];
By default it uses the locale of your system, but you can change that and lots of other properties, see the NSNumberFormatter API docs.
Assuming the price is held in a float, you probably want +localizedStringWithFormat:.
NSString *priceString = [NSString localizedStringWithFormat:#"$ %'.2f",price];
Hmmm... Apple says they follow the IEEE standard for printf, so it should accept the ' flag, but it doesn't work on Tiger. NSNumberFormatter it is.
You need to get rid of the ' character
So, just have this:
NSString *priceString = [NSString localizedStringWithFormat:#"$ %.2f", price];
NSString *formatedNumbers = [NSNumberFormatter localizedStringFromNumber:myNumber numberStyle:NSNumberFormatterCurrencyStyle];