convert NSString to long value [duplicate] - ios

How can I convert a NSString containing a number of any primitive data type (e.g. int, float, char, unsigned int, etc.)? The problem is, I don't know which number type the string will contain at runtime.
I have an idea how to do it, but I'm not sure if this works with any type, also unsigned and floating point values:
long long scannedNumber;
NSScanner *scanner = [NSScanner scannerWithString:aString];
[scanner scanLongLong:&scannedNumber];
NSNumber *number = [NSNumber numberWithLongLong: scannedNumber];
Thanks for the help.

Use an NSNumberFormatter:
NSNumberFormatter *f = [[NSNumberFormatter alloc] init];
f.numberStyle = NSNumberFormatterDecimalStyle;
NSNumber *myNumber = [f numberFromString:#"42"];
If the string is not a valid number, then myNumber will be nil. If it is a valid number, then you now have all of the NSNumber goodness to figure out what kind of number it actually is.

You can use -[NSString integerValue], -[NSString floatValue], etc. However, the correct (locale-sensitive, etc.) way to do this is to use -[NSNumberFormatter numberFromString:] which will give you an NSNumber converted from the appropriate locale and given the settings of the NSNumberFormatter (including whether it will allow floating point values).

Objective-C
(Note: this method doesn't play nice with difference locales, but is slightly faster than a NSNumberFormatter)
NSNumber *num1 = #([#"42" intValue]);
NSNumber *num2 = #([#"42.42" floatValue]);
Swift
Simple but dirty way
// Swift 1.2
if let intValue = "42".toInt() {
let number1 = NSNumber(integer:intValue)
}
// Swift 2.0
let number2 = Int("42')
// Swift 3.0
NSDecimalNumber(string: "42.42")
// Using NSNumber
let number3 = NSNumber(float:("42.42" as NSString).floatValue)
The extension-way
This is better, really, because it'll play nicely with locales and decimals.
extension String {
var numberValue:NSNumber? {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
return formatter.number(from: self)
}
}
Now you can simply do:
let someFloat = "42.42".numberValue
let someInt = "42".numberValue

For strings starting with integers, e.g., #"123", #"456 ft", #"7.89", etc., use -[NSString integerValue].
So, #([#"12.8 lbs" integerValue]) is like doing [NSNumber numberWithInteger:12].

You can also do this:
NSNumber *number = #([dictionary[#"id"] intValue]]);
Have fun!

If you know that you receive integers, you could use:
NSString* val = #"12";
[NSNumber numberWithInt:[val intValue]];

Here's a working sample of NSNumberFormatter reading localized number NSString (xCode 3.2.4, osX 10.6), to save others the hours I've just spent messing around. Beware: while it can handle trailing blanks ("8,765.4 " works), this cannot handle leading white space and this cannot handle stray text characters. (Bad input strings: " 8" and "8q" and "8 q".)
NSString *tempStr = #"8,765.4";
// localization allows other thousands separators, also.
NSNumberFormatter * myNumFormatter = [[NSNumberFormatter alloc] init];
[myNumFormatter setLocale:[NSLocale currentLocale]]; // happen by default?
[myNumFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
// next line is very important!
[myNumFormatter setNumberStyle:NSNumberFormatterDecimalStyle]; // crucial
NSNumber *tempNum = [myNumFormatter numberFromString:tempStr];
NSLog(#"string '%#' gives NSNumber '%#' with intValue '%i'",
tempStr, tempNum, [tempNum intValue]);
[myNumFormatter release]; // good citizen

I wanted to convert a string to a double. This above answer didn't quite work for me. But this did: How to do string conversions in Objective-C?
All I pretty much did was:
double myDouble = [myString doubleValue];

Thanks All! I am combined feedback and finally manage to convert from text input ( string ) to Integer. Plus it could tell me whether the input is integer :)
NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber * myNumber = [f numberFromString:thresholdInput.text];
int minThreshold = [myNumber intValue];
NSLog(#"Setting for minThreshold %i", minThreshold);
if ((int)minThreshold < 1 )
{
NSLog(#"Not a number");
}
else
{
NSLog(#"Setting for integer minThreshold %i", minThreshold);
}
[f release];

I think NSDecimalNumber will do it:
Example:
NSNumber *theNumber = [NSDecimalNumber decimalNumberWithString:[stringVariable text]]];
NSDecimalNumber is a subclass of NSNumber, so implicit casting allowed.

What about C's standard atoi?
int num = atoi([scannedNumber cStringUsingEncoding:NSUTF8StringEncoding]);
Do you think there are any caveats?

You can just use [string intValue] or [string floatValue] or [string doubleValue] etc
You can also use NSNumberFormatter class:

you can also do like this code 8.3.3 ios 10.3 support
[NSNumber numberWithInt:[#"put your string here" intValue]]

NSDecimalNumber *myNumber = [NSDecimalNumber decimalNumberWithString:#"123.45"];
NSLog(#"My Number : %#",myNumber);

Try this
NSNumber *yourNumber = [NSNumber numberWithLongLong:[yourString longLongValue]];
Note - I have used longLongValue as per my requirement. You can also use integerValue, longValue, or any other format depending upon your requirement.

Worked in Swift 3
NSDecimalNumber(string: "Your string")

I know this is very late but below code is working for me.
Try this code
NSNumber *number = #([dictionary[#"keyValue"] intValue]]);
This may help you. Thanks

extension String {
var numberValue:NSNumber? {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
return formatter.number(from: self)
}
}
let someFloat = "12.34".numberValue

Related

NSNumber numberFromString not placed decimals

I am trying to convert NSString to NSNumber and it seems to create a decimal point issue here.
NSString *str = #"515.51515";
NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber * myNumber = [f numberFromString:str];
NSLog(#"Number here:%#",myNumber);
[f release];
& result print is
2015-03-01 08:09:28.353 myApp [57376:2086924] Number here: 515.5151499999999
Actual debug log picture here
but actually it should be 515.51515 rather 515.5151499999999.
I tried all comibination with f.usesSignificantDigits & f.maximumFractionDigits =10 but no luck.
please let me know How to fix this?
RMaddy is correct, floating point numbers will be a bit off.
Since an NSDecimalNumber is an NSNumber you can use:
NSNumber *number = [NSDecimalNumber decimalNumberWithString:#"515.51515"];
Try to use construction:
NSNumber *myNumber = [NSNumber numberWithFloat:[str floatValue]];
I think it should work correctly.

Float value resets after Adding

I start off with a number, lets say 250. I add all sorts of numbers, but anytime I add a high number like 2,000 it adds correctly. Then I add 3. The new number comes out to 5 like it thought 2,000 was 2.0. I do not know why it is doing this.
float start = self.amountLabel.text.floatValue;
float changeAmount = self.amountField.text.floatValue;
float newValue;
if (determConfirm == 1) {
newValue = start + changeAmount;
} else {
newValue = start - changeAmount;
}
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setMaximumFractionDigits:5];
[formatter setRoundingMode: NSNumberFormatterRoundUp];
NSString *numberString = [formatter stringFromNumber:[NSNumber numberWithFloat:newValue]];
[[NSUserDefaults standardUserDefaults] setValue:numberString forKey:#"newValue"];
[[NSUserDefaults standardUserDefaults] synchronize];
self.amountLabel.text = numberString;
self.amountField.text = #"0.00";
[self.amountField resignFirstResponder];
The problem is the use of floatValue to convert the formatted number text to a number. floatValue only works as expected if the text is unformatted (no commas) and uses the period for the decimal separator.
Since you store a formatted number in the field, it only works with small numbers and in certain locales.
Replace your use of floatValue on the text with the same NSNumberFormatter used to format the number. Use it to parse the text and give you an NSNumber (which you can then call floatValue on).
Just a guess as it's hard by looking at your code, but maybe you want this:
float newValue = start;
if (determConfirm == 1) {
newValue += changeAmount;
} else {
newValue -= changeAmount;
}

NSNumber to float Value

When I convert NSNumber to float value using 'floatValue', there is a difference in precision. Example, I have a NSNumber 'myNumber' having value 2.3, and if I convert myNumber to float using 'floatValue', its value becomes, 2.29999. But I need exactly 2.30000. There is no problem with number of zeros after 2.3, I need '2.3' instead of '2.9'.
How can I do so?
I had similar situation where I was reading value and assigning it back to float variable again.
My Problem statement:
NSString *value = #"553637.90";
NSNumber *num = #([value floatValue]); // 1. This is the problem. num is set to 553637.875000
NSNumberFormatter *decimalStyleFormatter = [[NSNumberFormatter alloc] init];
[decimalStyleFormatter setMaximumFractionDigits:2];
NSString *resultString = [decimalStyleFormatter stringFromNumber:num]; // 2. string is assigned with rounded value like 553637.88
float originalValue = [resultString floatValue]; // 3. Hence, originalValue turns out to be 553637.88 which wrong.
Following worked for me after changing lines:
NSNumber *num = #([value doubleValue]); // 4. doubleValue preserves value 553637.9
double originalvalue = [resultString doubleValue]; // 5. While reading back, assign to variable of type double, in this case 'originalValue'
I hope this would be helpful. :)
If you need exact precision, don't use float. Use a double if you need better precision. That still won't be exact. You could multiply myNumber by 10, convert to an unsigned int and perform your arithmetic on it, convert back to a float or double and divide by 10 and the end result might be more precise. If none of these are sufficiently precise, you might want to look into an arbitrary precision arithmetic library such as GNU MP Bignum.
I've done the following but it is showing me correctly
NSNumber *num = [NSNumber numberWithFloat:2.3];
float f = [num floatValue];
NSLog(#"%f", f);
You can play with something like this:
float x = 2.3f;
NSNumber *n = [NSNumber numberWithFloat:x];
NSNumberFormatter *fmt = [[NSNumberFormatter alloc] init];
[fmt setPositiveFormat:#"0.#"];
NSString *s = [fmt stringFromNumber:n];
float f = [s floatValue];

NSNumberformatter add extra zero

I'm looking for a way to display "1" as "01", so basically everything below 10 should have a leading 0.
What would be the best way to do this?
I know I can just use a simple if structure to do this check, but this should be possible with NSNumberformatter right?
If you just want an NSString, you can simply do this:
NSString *myNumber = [NSString stringWithFormat:#"%02d", number];
The %02d is from C. %nd means there must be at least n characters in the string and if there are less, pad it with 0's. Here's an example:
NSString *example = [NSString stringWithFormat:#"%010d", number];
If the number variable only was two digits long, it would be prefixed by eight zeroes. If it was 9 digits long, it would be prefixed by a single zero.
If you want to use NSNumberFormatter, you could do this:
NSNumberFormatter * numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setPaddingPosition:NSNumberFormatterPadBeforePrefix];
[numberFormatter setPaddingCharacter:#"0"];
[numberFormatter setMinimumIntegerDigits:10];
NSNumber *number = [NSNumber numberWithInt:numberVariableHere];
----UPDATE------
I think this solves your problem:
[_minutes addObject:[NSNumber numberWithInt:i]];
return [NSString stringWithFormat:#"%02d", [[_minutes objectAtIndex:row] intValue]];
FIXED for Swift 3
let x = 999.1243
let formatter = NumberFormatter()
formatter.minimumFractionDigits = 1 // for float
formatter.maximumFractionDigits = 1 // for float
formatter.minimumIntegerDigits = 10 // digits do want before decimal
formatter.paddingPosition = .beforePrefix
formatter.paddingCharacter = "0"
let s = formatter.string(from: NSNumber(floatLiteral: x))!
OUTPUT
"0000000999.1"

Convert a string into an int

I'm having trouble converting a string into an integer. I googled it but all I can find is how to convert an int into a string. Does anyone know how to do it the other way around? Thanks.
See the NSString Class Reference.
NSString *string = #"5";
int value = [string intValue];
How about
[#"7" intValue];
Additionally if you want an NSNumber you could do
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter numberFromString:#"7"];
I use:
NSInteger stringToInt(NSString *string) {
return [string integerValue];
}
And vice versa:
NSString* intToString(NSInteger integer) {
return [NSString stringWithFormat:#"%d", integer];
}
This is the simple solution for converting string to int
NSString *strNum = #"10";
int num = [strNum intValue];
but when you are getting value from the textfield then,
int num = [txtField.text intValue];
where txtField is an outlet of UITextField
Swift 3.0:
Int("5")
or
let stringToConvert = "5"
Int(stringToConvert)
I had to do something like this but wanted to use a getter/setter for mine. In particular I wanted to return a long from a textfield. The other answers all worked well also, I just ended up adapting mine a little as my school project evolved.
long ms = [self.textfield.text longLongValue];
return ms;
NSString *string = /* Assume this exists. */;
int value = [string intValue];
Very easy..
int (name of integer) = [(name of string, no ()) intValue];
Yet another way: if you are working with a C string, e.g. const char *, C native atoi() is more convenient.
You can also use like :
NSInteger getVal = [self.string integerValue];
To convert an String number to an Int, you should do this:
let stringNumber = "5"
let number = Int(stringNumber)

Resources