Convert string to float in Objective-C - objective-c

How do I convert a string to a float in Objective-C?
I am trying to multiply a couple of strings I am getting back from JSON:
float subTotal = [[[[purchaseOrderItemsJSON objectAtIndex:i] objectAtIndex:j] objectForKey:#"Price"] floatValue];
NSLog(#"%#", subTotal);
This gives me: (null) in the console. I know that there is a valid string coming out of that array because I am already using it to display its value in a label.

your_float = [your_string floatValue];
EDIT:
try this:
NSLog(#"float value is: %f", your_float);

The proper way of doing this is
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
numberFormatter.numberStyle = NSNumberFormatterDecimalStyle;
float value = [numberFormatter numberFromString:#"32.12"].floatValue;

Related

Not seeing the decimal from a string when converted into NSDecimalNumer

I can't see to find the answer to this, but I have a string that has a decimal point in it, and when I try to convert it to a NSDecimalNumber I only get back the whole number, not the decimal or what would come after it. This is what I am trying:
someText.text = #"200.00";
tempAmountOwed = [NSDecimalNumber decimalNumberWithString:someText.text]; // gives me back 200
I can't seem to figure out if the decimalNumberWithString method is stripping out my decimal and ignoring what comes after it.
Thanks for the help!
You can use the method decimalNumberWithString: locale: method.
for eg:-
The code:
NSLog(#"%#", [NSDecimalNumber decimalNumberWithString:#"200.00"]);
NSLog(#"%#", [NSDecimalNumber decimalNumberWithString:#"200.00" locale:NSLocale.currentLocale]);
Gives following log:
200
200.00
Hope this Helps!
That's perfectly normal. If your decimal String doesn't contain fractions it won't print them. If you want to print them you can use a NSNumberFormatter or convert it to a float and print it with %.2f to do so:
NSString *text = #"200.00";
NSDecimalNumber *number = [NSDecimalNumber decimalNumberWithString:text];
NSLog(#"%#", number); //this will print "200"
//solution #1
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
numberFormatter.numberStyle = NSNumberFormatterDecimalStyle;
numberFormatter.minimumFractionDigits = 2;
NSLog(#"%#", [numberFormatter stringFromNumber:number]); //this will print "200.00"
//solution #2
CGFloat number = [text floatValue];
NSLog(#"%.2f", number); //this will print "200.00"

How to display leading zero in double

I need to make NSNumber to display only 4 decimal points. This part of code is works, but it outputs result without leading zero.
double resultRoundToDecimal = [result doubleValue];
NSNumberFormatter *resultFormatter = [[NSNumberFormatter alloc] init];
[resultFormatter setRoundingMode:NSNumberFormatterRoundHalfUp];
[resultFormatter setMaximumFractionDigits:4];
resultData = [resultFormatter stringFromNumber:[NSNumber numberWithDouble:resultRoundToDecimal]];
For example:
1/3 = .3333
I want:
1/3 = 0.3333
How I can to do this?
You could choose to use string formatter too, like below
float val=1./3;
NSString *resultData=[NSString stringWithFormat:#"%0.4f",val];
NSLog(#"Result = %#",resultData);
Prepend a 0 or use number formatter.
NSString *printStr = #"0";
printStr = [NSString stringByAppendingString: resultData];
Otherwise, you could use a number formatter or something similar. If your just outputting a string why not do that?
https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSNumberFormatter_Class/Reference/Reference.html

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.

Convert a number with a comma into a number with point. (Cocoa Touch)

I'm trying to code a calculator with XCode, but then I saw that Numbers with a comma are just cutted of after the comma.
I am getting the Numbers with this code out of the textfield.
-(IBAction)Additionbutton:(id)sender{
NSString *firstString = field1.text;
NSString *secondString = field2.text;
float num1;
float num2;
float output;
num1 = [firstString floatValue];
num2 = [secondString floatValue];
output = num1 + num2
Solutionfield.text = [ [NSString alloc] initWithFormat:#"%.2f",output] ;
Is it possible to set the calculation that way, that it is able to handle points AND commas or do I have to convert them and if so, how can I do this?
Thank you :)
Maybe you should use: NSNumberFormatter
How to convert an NSString into an NSNumber
I have experienced the same thing this morning, following solution worked for me:
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
NSNumber *aNumber = [NSNumber numberWithFloat:[[yourFloatAsString stringByReplacingOccurrencesOfString:#"," withString:#"" ] floatValue]];
[numberFormatter setNumberStyle:kCFNumberFormatterDecimalStyle];
NSString *formattedNumber;
formattedNumber = [numberFormatter stringFromNumber:aNumber];
NSLog(#"formattedNumber: %#", formattedNumber);
Obviously not the most efficient solution possible. It works, but if you have some time I strongly suggest you to have a look at NSNumberFormatter Class Reference

How to convert an NSString into an NSNumber

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