Format string, integer with leading zeros - objective-c

I want to convert an integer value to a string with leading zeroes (if necessary) such that the string has 3 total characters. For example, 5 would become "005", and 10 would become "010".
I've tried this code:
NSString* strName = [NSString stringWithFormat:#"img_00%d.jpg", i];
This partially works, but if i has the value of 10, for example, the result is img_0010.jpg, not img_010.jpg.
Is there a way to do what I want?

Use the format string "img_%03d.jpg" to get decimal numbers with three digits and leading zeros.

For posterity: this works with decimal numbers.
NSString *nmbrStr = #"0033620340000" ;
NSDecimalNumber *theNum = [[NSDecimalNumber decimalNumberWithString:nmbrStr]decimalNumberByAdding: [NSDecimalNumber one]] ;
NSString *fmtStr = [NSString stringWithFormat:#"%012.0F",[theNum doubleValue]] ;
Though this information is hard to find, it is actually documented here in the second paragraph under Formatting Basics. Look for the % character.
https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Strings/Articles/FormatStrings.html

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

Convert 0x001234AB to NSString "001234AB"

I used Google, and Bing and SO, and I get literally hundreds of answers how to convert string to an integer, but cannot find a single example how to convert a number to a string in HEX base. And I need to convert thousands (into the same string) so a faster method is preferred.
int x = 0x001234ab;
NSString str;
<------- what should behere?
NSLog(str); // outputs "001234AB" or "001234ab"
NSLog(#"%x", x);
Or if you want it in string.
NSString *s = [NSString stringWithFormat:#"%x", x];
If you want leading zeros your format will look like this
#"%0yx"
where y is number of zeros (for your example 8).

Objective-C: extract numeric fraction in string and convert it to a real number

I have got some strings, they look like this: 1/2 pound steak. Now I need to split the string afetr 1/2 and convert 1/2 to a number. It can be that the string contains more spaceses and 1/2 can also be 1/6 or any other number. Anyone got any idea how to split and convert?
This should solve the problem:
NSString *input = #"3/4 pounds of sugar";
// trim white space at the beginning and end
input = [input stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
// define charater set to split
NSCharacterSet *chSet = [NSCharacterSet characterSetWithCharactersInString:#" /"];
// split string into array of strings by charaters '/' and ' '
NSArray *split = [input componentsSeparatedByCharactersInSet:chSet];
// the result of the fraction inside result
double result = [split[0] doubleValue] / [split[1] doubleValue];

What happened to Objective-C's "stringWithFormat:" method?

When I define
NSString *testString = [NSString stringWithFormat:#"%4d", 543210];
then testString is #"543210", instead of #"3210"
This used to work in Xcode v4.3.1 but now I upgraded to v4.6 and it stopped working.
Any ideas?
then testString is #"543210", instead of #"3210"
That's the correct behavior anyway. The %Nd format specifier doesn't limit the field with of the number being formatted - it only pads it with space if the field with is greater than the number of characters required to represent the number. If you got 3210 previously, that's erroneous.
If you want to format a number so at most its last four digits are printed, then you can do something like this:
NSString *numStr = [NSString stringWithFormat:#"%d", 543210]; // or whatever
if (numStr.length > 4) {
numStr = [numStr substringFromIndex:numStr.length - 4];
}
Another alternative, has the benefit of being short:
NSString *testString = [NSString stringWithFormat:#"%4d", 543210 % 10000];
The modulus operator % returns the remainder, so if you % 10000 you get the 4 least significant digits.

More precise square root of a value

To get a square root value of mainlabelString, I am using
- (IBAction)rootPressed:(id)sender
{
NSString *mainLabelString = mainLabel.text;
int mainLabelValue = [mainLabelString longLongValue];
NSString *calculatedValue = [NSString stringWithFormat: #"%f", sqrt(mainLabelValue)];
mainLabel.text = calculatedValue;
}
And although it does work with numbers such as 88, from which I get 9.380832, it does not for example work with that number, for which it says the square root is 3.000000 (instead of 3.062814).
I tried replacing longLongValue with doubleValue and integerValue but it doesn't change it.
What's wrong?
If the value into the text field is like #"9.0001", getting the long long value truncates the decimal part.You said that you also have tried doubleValue, but I suspect that you did something like this:
int mainLabelValue = [mainLabelString doubleValue];
Instead of:
double mainLabelValue = [mainLabelString doubleValue];
In the first case the number loses the decimal part too, because an int can't store the decimal part, nor a long long int.
Let me know how you exactly tried to retrieve the double value of the text field.
Use NSNumberFormatter it provides very wide range and different styles(Decimaland scientific etc).documentation