objective c - Xcode long int display with formatting - objective-c

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.

Related

How to convert NSString to NSInteger in iPhone application?

NSString * addString=[arrayyyy componentsJoinedByString:#","];
NSLog(#"add string is: %#",addString);// result is: 45,1
Now I want to convert above string into integer.
I have tried this:
NSInteger myInt=[addString intValue];
//NSLog(#"myInt is: %d",myInt);// result is: 45
If you expected 45.1 then there are two things wrong :
45.1 is not an integer. You would have to use floatValue to read the value.
45,1 (notice the comma) is not a valid float number. While 45,1 is valid in some locale (i.e. in french its 1 000,25 instead of 1,000.25) you would have to convert the string with an NSNumberFormatter before reading the floatValue.
.
// Can't compile and verify this right now, so please bear with me.
NSString *str = #"45,1";
NSNumberFormatter *formatter = [[[NSNumberFormatter alloc] init] autorelease];
NSLocale *locale = [[[NSLocale alloc] initWithLocaleIdentifier:#"fr_FR"] autorelease]; // lets say French from France
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setLocale:locale];
float value = [[formatter numberFromString:str] floatValue]; // value = 45.1
Try out NSExpression which works with mathematical symbols too (i.e. +, -, /, *):
NSNumber *numberValue = [[NSExpression expressionWithFormat:inputString] expressionValueWithObject:nil context:nil];
// do something with numberValue
From reading the question a lot, I think I may understand what you want.
The starting point seems to be:
NSLog(#"add string is: %#",addString);// result is: 45,1
And the current ending point is:
NSLog(#"myInt is: %d",myInt);// result is: 45
But it seems that you still want to print out 45,1
My guess on this is that you have an array of 2 strings [#"45",#"1"] called arrayyyy and you want to print out both values as integers. If this is so then what I think you want is:
NSInteger myInt1 = [[arrayyyy objectAtIndex:0] intValue];
NSInteger myInt2 = [[arrayyyy objectAtIndex:1] intValue];
NSLog(#"add string is: %d,%d",myInt1,myInt2);
Note This will crash horribly with an NSRangeException if there are not at least two strings in the array. So at the very least you should do:
NSInteger myInt1 = -1;
NSInteger myInt2 = -1;
if ([arrayyyy length] >0) myInt1 = [[arrayyyy objectAtIndex:0] intValue];
if ([arrayyyy length] >1) myInt2 = [[arrayyyy objectAtIndex:1] intValue];
NSLog(#"add string is: %d,%d",myInt1,myInt2);
But even this is bad as it assumes that the guard value of -1 will not be present in the actual data.

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...

formatting value in a string to have a decimal separator

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

Objective-c convert Long and float to String

I need to convert two numbers to string in Objective-C.
One is a long number and the other is a float.
I searched on the internet for a solution and everyone uses stringWithFormat: but I can't make it work.
I try
NSString *myString = [NSString stringWithFormat: #"%f", floatValue]
for 12345678.1234 and get "12345678.00000" as output
and
NSString *myString = [NSString stringWithFormat: #"%d", longValue]
Can somebody show me how to use stringWithFormat: correctly?
This article discusses how to use various formatting strings to convert numbers/objects into NSString instances:
String Programming Guide: Formatting String Objects
Which use the formats specified here:
String Programming Guide: String Format Specifiers
For your float, you'd want:
[NSString stringWithFormat:#"%1.6f", floatValue]
And for your long:
[NSString stringWithFormat:#"%ld", longValue] // Use %lu for unsigned longs
But honestly, it's sometimes easier to just use the NSNumber class:
[[NSNumber numberWithFloat:floatValue] stringValue];
[[NSNumber numberWithLong:longValue] stringValue];
floatValue has to be a double. At least this compiles correctly and does what is expected on my machine
Floats can only store about 8 decimal digits and your number 12345678.1234 requires more precision than that, hence only about the 8 most significant digit are stored in a float.
double floatValue = 12345678.1234;
NSString *myString = [NSString stringWithFormat: #"%f", floatValue];
results in
2011-11-04 11:40:26.295 Test basic command line[7886:130b] floatValue = 12345678.123400
You should use NSNumberFormatter eg:
NSNumberFormatter * nFormatter = [[NSNumberFormatter alloc] init];
[nFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber *num = [nFormatter numberFromString:#"12345678.1234"];
[nFormatter release];

How do I round a NSNumber to zero decimal spaces

How do I round an NSNumber to zero decimal spaces, in the following line it seems to keep the decimal spaces:
NSNumber holidayNightCount = [NSNumber numberWithDouble:sHolidayDuration.value];
Typically casting to int truncates. For example, 3.4 becomes 3 (as is desired), but 3.9 becomes 3 also. If this happens, add 0.5 before casting
int myInt = (int)(sHolidayDuration.value + 0.5);
Here's a bit of a long winded approach
float test = 1.9;
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setRoundingMode:NSNumberFormatterRoundHalfUp];
[formatter setMaximumFractionDigits:0];
NSLog(#"%#",[formatter stringFromNumber:[NSNumber numberWithFloat:test]]);
[formatter release];
If you only need an integer why not just use an int
int holidayNightCount = (int)sHolidayDuration.value;
By definition an int has no decimal places
If you need to use NSNumber, you could just cast the Double to Int and then use the int to create your NSNumber.
int myInt = (int)sHolidayDuration.value;
NSNumber holidayNightCount = [NSNumber numberWithInt:myInt];
you can also do the following: int roundedRating = (int)round(rating.floatValue);
Floor the number using the old C function floor() and then you can create an NSInteger which is more appropriate, see:
https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man3/floor.3.html ....
NSInteger holidayNightCount = [NSNumber numberWithInteger:floor(sHolidayDuration.value)].integerValue;
Further information on the topic here: http://eureka.ykyuen.info/2010/07/19/objective-c-rounding-float-numbers/
Or you could use NSDecimalNumber features for rounding numbers.