Dynamically format a float in a NSString - objective-c

Consider this:
NSString *whatever=[NSString stringWithFormat:#"My float: %.2f",aFloat];
This will round my aFloat to 2 decimal places when building the string whatever
Suppose I want the 2 in this statement to be assignable, such that, based on the value of aFloat I might have it show 2 or 4 decimal places. How can I build this into stringWithFormat?
I want to be able to do this without an if that simply repeats the entire line for different cases, but rather somehow dynamically change just the %.2f portion.

The proper answer is to use an NSNumberFormatter.
However, the easy answer that uses format strings is to use the asterisk specifier. According to the Apple documentation the format string conforms to the IEEE printf specification. This specification states the following:
A field width, or precision, or both, may be indicated by an asterisk ( '*' ). In this case an argument of type int supplies the field width or precision.
This means that
int precision = 2;
NSString *whatever=[NSString stringWithFormat:#"My float: %.*f", precision,aFloat];
// Asterisk in place of 2^^ ^^^^^^^^^ int variable
should work. I have to say, I haven't tried it though, I tend to use NSNumberFormatters.

You will need to build the format first:
NSInteger precision = 2;
NSString *format = [#"My float: %." stringByAppendingFormat:#"%d", precision];
format = [format stringByAppendingString:#"f"];
NSString *whatever=[NSString stringWithFormat:format, aFloat];

Escape % as %% to build format strings:
NSUInteger digits = aFloat > 10.0f ? 2 : 4;
NSString *format = [NSString stringWithFormat:#"My float: %%.%if", digits];
NSString *whatever = [NSString stringWithFormat:format, aFloat];

Related

How to define a variable string format specifier

I have this line of code
// valueX is a long double (long double is a huge floating point)
NSString *value = [NSString stringWithFormat: #"%.10Lg", valueX];
This format specifier is specifying up to 10 decimal digits but I don't want to hard code this to 10.
I have this variable numberOfDigits that I want to be used to define the number of digits. For those itching to down vote this question, it is not so easy as it seems. I cannot substitute the 10 with %# because %.10Lg is a format specifier by itself.
OK, I can create a bunch of strings like #"%.5Lg", #"%.8Lg", #"%.9Lg"... and switch that, but I wonder if there is another way...
There is, if you read the manual pages for format specifiers. You can replace the precision with *, which means it will get taken from a parameter instead.
int numDigits = 10;
NSString *value = [NSString stringWithFormat:#"%.*Lg", numDigits, valueX];
I couldn't find this in the core foundation reference, but I know that this is written in the man 3 printf man page.
Dietrich's answer is the simplest and therefore best. Note that even if there wasn't a built-in way to specify the number of digits with a parameter you could still have done it by first building your format string and then using it:
- (NSString *) stringFromValue: (long double) value digits: (int) digits; {
//First create a format string. Use "%%" to escape the % escape char.
NSString *formatString =[NSString stringWithFormat: #"%%.%dLg", digits];
return [NSString stringWithFormat: formatString, value];
}

How do I convert a decimal to hexadecimal using Objective C?

I've been working on a calculator and I wanted to implement conversions from decimal to octal and from decimal to hexadecimal. I'm new to Xcode and Objective C, but I've managed to get a conversion from decimal to octal, it just doesn't seem to work with hexadecimal.
Here's the code I've written to convert a double to octal:
double result = 0;
...
double decToOct = [self popOperand];
NSString *oct = [NSString stringWithFormat:#"%llo", (long long)decToOct];
result = [oct doubleValue];
Using the same scheme (obviously that includes changing #"%llo" with #"%llx") the conversion to hexadecimal works up to a certain point. It does numbers 0 through 9 just fine, but once it hits 10, it comes up as 0. To test, I also input 5395 and it displayed 1513, the desired result.
Because of this, I can only assume that for some reason my code does not want to input the actual letters of the hexadecimal values (e.g. 11 would convert to B but it shows up as 0) .
Any suggestions? Thanks in advance.
UPDATE:
In addition, I have also been using this to display the result:
double result = [self.brain performOperation:operation];
self.display.text = [NSString stringWithFormat:#"%g", result];
result, as listed from the top, is an argument which is eventually returned here, to self.brain performOperation:operation. This is supposed to handle the display of all operations, including: addition, multiplication, etc. but also octal and hexadecimal. Again, it works fine with octal, but not with hexadecimal.
Try this, May be it will help you. Please do let me know if i am wrong here:--->
NSString *decStr = #"11";
NSString *hexStr = [NSString stringWithFormat:#"%lX",
(unsigned long)[dec integerValue]];
NSLog(#"%#", hexStr);
If you know your string only contains a valid decimal number then the simplest way would be:
NSString *dec = #"254";
NSString *hex = [NSString stringWithFormat:#"0x%lX",
(unsigned long)[dec integerValue]];
NSLog(#"%#", hex);

Variable interpolation inside printf-style formatting functions

Is there a way to pass a variable for the floating point precision parameter in printf-style string formatting functions in Objective-C (or even C)? For example, in TCL and other scripting languages, I can do something like this:
set precision 2
puts [format "%${precision}f" 3.14159]
and the output will be, of course, 3.14. I would like to do something similar in Objective-C:
float precision = 2
NSString *myString = [NSString stringWithFormat:#".2f", 3.14159]
except that I would like to include precision as a variable. How can this be done?
Yes, the string format specifiers for printf, which are used by Cocoa for formatting, include a variable-precision specifier, * placed after the decimal point:
int precision = 3;
NSLog(#"%.*f", precision, 3.14159);
NSString *myString = [NSString stringWithFormat:#".*f", precision, 3.14159];
You can do it by making your format string a variable, and then passing that to stringWithFormat, like this:
float precision = 2;
NSString* formatString = [NSString stringWithFormat:#"%%.%df", precision];
NSString* myString = [NSString stringWithFormat:formatString, 3.14159];
The format string says you want a "%" symbol followed by a "." and then the value stored in the variable "precision" followed by "f".

Padding a number in NSString

I have an int, for example say 45. I want to get NSString from this int padded with 4 zeroes. So the result would be : #"0045". Similar, if the int is 9, I want to get: #"0009".
I know I can count the number of digits, then subtract it from how many zeroes i want padded, and prepend that number to the string, but is there a more elegant way? Thanks.
Try this:
NSLog(#"%04d", 45);
NSLog(#"%04d", 9);
If it works, then you can get padded number with
NSString *paddedNumber = [NSString stringWithFormat:#"%04d", 45];
NSString *otherPaddedNumber = [NSString stringWithFormat:#"%04d", 9];
Update
If you want to have arbitrary number you'd have to create a format for your format:
// create "%04d" format string
NSString *paddingFormat = [NSString stringWithFormat:#"%%0%dd", 4];
// use it for padding numbers
NSString *paddedNumber = [NSString stringWithFormat:paddingFormat, 45];
NSString *otherPaddedNumber = [NSString stringWithFormat:paddingFormat, 9];
Update 2
Please see #Ibmurai's comment on how to properly pad a number with NSLog.
Excuse me for answering this question with an already accepted answer, but the answer (in the update) is not the best solution.
If you want to have an arbitrary number you don't have to create a format for your format, as IEEE printf supports this. Instead do:
NSString *paddedNumber = [NSString stringWithFormat:#"%0*d", 4, 45];
NSString *otherPaddedNumber = [NSString stringWithFormat:#"%0*d", 4, 9];
While the other solution works, it is less effective and elegant.
From the IEEE printf specification:
A field width, or precision, or both, may be indicated by an asterisk ( '*' ). In this case an argument of type int supplies the field width or precision.
Swift version as Int extension (one might wanna come up with a better name for that method):
extension Int
{
func zeroPaddedStringValueForFieldWidth(fieldWidth: Int) -> String
{
return String(format: "%0*d", fieldWidth, self)
}
}
Examples:
print( 45.zeroPaddedStringValueForFieldWidth(4) ) // prints "0045"
print( 9.zeroPaddedStringValueForFieldWidth(4) ) // prints "0009"

How to convert a string into double and vice versa?

I want to convert a string into a double and after doing some math on it, convert it back to a string.
How do I do this in Objective-C?
Is there a way to round a double to the nearest integer too?
You can convert an NSString into a double with
double myDouble = [myString doubleValue];
Rounding to the nearest int can then be done as
int myInt = (int)(myDouble + (myDouble>0 ? 0.5 : -0.5))
I'm honestly not sure if there's a more streamlined way to convert back into a string than
NSString* myNewString = [NSString stringWithFormat:#"%d", myInt];
To really convert from a string to a number properly, you need to use an instance of NSNumberFormatter configured for the locale from which you're reading the string.
Different locales will format numbers differently. For example, in some parts of the world, COMMA is used as a decimal separator while in others it is PERIOD — and the thousands separator (when used) is reversed. Except when it's a space. Or not present at all.
It really depends on the provenance of the input. The safest thing to do is configure an NSNumberFormatter for the way your input is formatted and use -[NSFormatter numberFromString:] to get an NSNumber from it. If you want to handle conversion errors, you can use -[NSFormatter getObjectValue:forString:range:error:] instead.
Adding to olliej's answer, you can convert from an int back to a string with NSNumber's stringValue:
[[NSNumber numberWithInt:myInt] stringValue]
stringValue on an NSNumber invokes descriptionWithLocale:nil, giving you a localized string representation of value. I'm not sure if [NSString stringWithFormat:#"%d",myInt] will give you a properly localized reprsentation of myInt.
Here's a working sample of NSNumberFormatter reading localized number String (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 such as "8,765.4 ", 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
olliej's rounding method is wrong for negative numbers
2.4 rounded is 2 (olliej's method gets this right)
−2.4 rounded is −2 (olliej's method returns -1)
Here's an alternative
int myInt = (int)(myDouble + (myDouble>0 ? 0.5 : -0.5))
You could of course use a rounding function from math.h
// Converting String in to Double
double doubleValue = [yourString doubleValue];
// Converting Double in to String
NSString *yourString = [NSString stringWithFormat:#"%.20f", doubleValue];
// .20f takes the value up to 20 position after decimal
// Converting double to int
int intValue = (int) doubleValue;
or
int intValue = [yourString intValue];
For conversion from a number to a string, how about using the new literals syntax (XCode >= 4.4), its a little more compact.
int myInt = (int)round( [#"1.6" floatValue] );
NSString* myString = [#(myInt) description];
(Boxes it up as a NSNumber and converts to a string using the NSObjects' description method)
For rounding, you should probably use the C functions defined in math.h.
int roundedX = round(x);
Hold down Option and double click on round in Xcode and it will show you the man page with various functions for rounding different types.
This is the easiest way I know of:
float myFloat = 5.3;
NSInteger myInt = (NSInteger)myFloat;
from this example here, you can see the the conversions both ways:
NSString *str=#"5678901234567890";
long long verylong;
NSRange range;
range.length = 15;
range.location = 0;
[[NSScanner scannerWithString:[str substringWithRange:range]] scanLongLong:&verylong];
NSLog(#"long long value %lld",verylong);
convert text entered in textfield to integer
double mydouble=[_myTextfield.text doubleValue];
rounding to the nearest double
mydouble=(round(mydouble));
rounding to the nearest int(considering only positive values)
int myint=(int)(mydouble);
converting from double to string
myLabel.text=[NSString stringWithFormat:#"%f",mydouble];
or
NSString *mystring=[NSString stringWithFormat:#"%f",mydouble];
converting from int to string
myLabel.text=[NSString stringWithFormat:#"%d",myint];
or
NSString *mystring=[NSString stringWithFormat:#"%f",mydouble];
I ended up using this handy macro:
#define STRING(value) [#(value) stringValue]