Objective-c convert Long and float to String - objective-c

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];

Related

Objective-C: Double to NSString with x-many decimals

I know that I can cast a double to a NSString with a specific amount of decimals like so:
double myDouble = 123.456789;
NSString *myString = [NSString stringWithFormat:#"%.4g", myDouble];
But how can I replace the number "4" in this example with a int variable?
Something like this doesn't work:
double myDouble = 123.456789;
int precision = 4;
NSString *myString = [NSString stringWithFormat:#"%.%dg", myDouble, precision];
Consider using NSNumberFormatter:
double myDouble = 123.456789;
int precision = 4;
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.minimumFractionDigits = precision;
formatter.maximumFractionDigits = precision;
NSString *myString = [formatter stringFromNumber:#(myDouble)];
Or, if you want this in scientific notation, you can alternatively specify something like:
formatter.numberStyle = NSNumberFormatterScientificStyle;
formatter.usesSignificantDigits = YES;
formatter.minimumSignificantDigits = precision;
formatter.maximumSignificantDigits = precision;
It just depends upon what precisely you're looking for.
This also has the virtue of also honoring the user's regional settings (e.g. if in Germany, the decimal separator is a comma, not a period).
If you need to force the locale setting (e.g. this is for creating something that will be exchanged with a web service that expects the data in a specified format), you can set the formatter's locale (e.g. [NSLocale localeWithLocaleIdentifier:#"en_US"]). But when presenting results in the user interface, you always want to honor the device's locale settings.
You can use asterisk in place of optional width and precision specifiers. And set them as arguments
double myDouble = 123.456789;
int width = 10;
int precision = 6;
NSString *s = [NSString stringWithFormat:#"%*.*g", width, precision, myDouble];
If you follow the links in the documentation for stringWithFormat you will discover the IEEE printf specification which describes the formats supported. That tells you that a field width or precision can be an * to indicate the actual value is supplied an an int argument, so what you want is:
NSString *myString = [NSString stringWithFormat:#"%.*g", intPrecision, myDouble];
double myDouble = 123.456789;
int precision = 4;
NSString *myString = [NSString stringWithFormat:#"%.*f", precision, myDouble];
NSLog(#"myString: '%#'", myString);
NSLog output:
myString: '123.4567'
This is by no means an optimal way of doing it, but it is a way.
You can do it in multiple steps
NSString *val = [NSString stringWithFormat: #"%d", 4];
NSString *head = [#"%." stringByAppendingString: val];
NSString *format = [head stringByAppendingString: #"g"];
NSString *result = [NSString stringWithFormat: format, 123.456789];
Or if you're really adventurous (for the sake of readability, don't EVER do this):
NSString *result = [NSString stringWithFormat: [[#"%." stringByAppendingString: [NSString stringWithFormat: #"%d", 4]] stringByAppendingString: #"g"], 123.456789];

Simple int to NSString conversion as in Java?

Is there any simple way how to initialize String in Objective-C with int such as in Java:
String myStr = 42 + "";
or I have to do
[NSString stringWithFormat:#"%d", 42];
everytime?
You could also use the NSNumber class for that:
NSNumber *number = [[NSNumber alloc] initWithInteger: val];
NSString *string = [number stringValue];
Perhaps not shorter, but it could be eventually faster.
Also you could create as said a helper method, than you wouldn't have to use more code than with the stringWithFormat: method.
Yes you have to do
[NSString stringWithFormat:#"%d", 42];
for Integer to string conversion.
Using a constant, like 42 in your example, you can write
NSString *myString = #"42";
Using a variable or expression, you can write
[NSString stringWithFormat:#"%d", myValue];

Convert float value to NSString

Do you know how can i convert float value to nsstring value because with my code, there is an error.
My Code :
- (float)percent:(float)a :(float)b{
return a / b * 100;
}
- (void)objectLoader:(RKObjectLoader*)objectLoader didLoadObjects:(NSArray*)objects {
// ....
float tx_nb_demande_portabilite = [self percent: [(NSNumber*) [stat nb_demande_portabilite] floatValue] :[(NSNumber*) [stat nb_users] floatValue]];
NSString *tx_nb_demande_portabilite_st = [NSString stringWithFormat:#"%#", tx_nb_demande_portabilite];
//....
}
The error :
EXC_BAD ACCESS for NSString *tx_nb_demande_portabilite_st = [NSString stringWithFormat:#"%#", tx_nb_demande_portabilite];
Thank you for your help.
You need to use %f format specifier for float, not %#.
NSString *str = [NSString stringWithFormat:#"%f", myFloat];
To use specific number of digits after decimal use %.nf where n is number of digits after decimal point.
// 3 digits after decimal point
NSString *str = [NSString stringWithFormat:#"%.3f", myFloat];
Obj-C uses C printf style formatting. Please check printf man page for all other possible formatting.
one more option:
NSString * str = [NSNumber numberWithFloat:value].stringValue;
#"%f" sounds like more appropriate format string for float.
[NSString stringWithFormat:#"%f", tx_nb_demande_portabilite];
A modern (and less verbose) approach would be:
NSString *str = #(myFloat).description;

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