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"
Related
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];
}
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).
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.
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];
I have a string called realEstateWorth with a value of $12,000,000.
I need this same string to remain a string but for any number (such as the one above) to be displayed as $12 MILLION or $6 MILLION. The point is it needs the words "MILLION" to come after the number.
I know there is nsNumberFormatter that can convert strings into numbers and vice versa but can it do what I need?
If anyone has any ideas or suggestions, it would be much appreciated.
Thank you!
So as I see it, you have two problems:
You have a string representation of something that's actually a number
You (potentially) have a number that you want formatted as a string
So, problem #1:
To convert a string into a number, you use an NSNumberFormatter. You've got a pretty simple case:
NSNumberFormatter *f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterCurrencyStyle];
NSNumber *n = [f numberFromString:#"$12,000,000"];
// n is 12000000
That was easy! Now problem #2:
This is trickier, because you want a mixed spell-out style. You could consider using an NSNumberFormatter again, but it's not quite right:
[f setNumberStyle:NSNumberFormatterSpellOutStyle];
NSString *s = [f stringFromNumber:n];
// s is "twelve million"
So, we're closer. At this point, you could perhaps maybe do something like:
NSInteger numberOfMillions = [n integerValue] / 1000000;
if (numberOfMillions > 0) {
NSNumber *millions = [NSNumber numberWithInteger:numberOfMillions];
NSString *numberOfMillionsString = [f stringFromNumber:millions]; // "twelve"
[f setNumberStyle:NSNumberFormatterCurrencyStyle];
NSString *formattedMillions = [f stringFromNumber:millions]; // "$12.00"
if ([s hasPrefix:numberOfMillionsString]) {
// replace "twelve" with "$12.00"
s = [s stringByReplacingCharactersInRange:NSMakeRange(0, [numberOfMillionsString length]) withString:formattedMillions];
// if this all works, s should be "$12.00 million"
// you can use the -setMaximumFractionDigits: method on NSNumberFormatter to fiddle with the ".00" bit
}
}
However
I don't know how well this would work in anything other than english. CAVEAT IMPLEMENTOR
Worst case scenario, you could implement a category on NSString to implement the behaviour you want.
In the method that you would do in that category you could take an NSNumberFormatter to bring that string to a number and by doing some modulo operation you could define if you need the word Million, or Billion, etc. and put back a string with the modulo for Million or other way you need it to be.
That way you could just call that method on your NSString like this :
NSString *humanReadable = [realEstateWorth myCustomMethodFromMyCategory];
And also.
NSString are immutable, so you can't change it unless you assign a new one to your variable.
I'd recommend storing this value as an NSNumber or a float. Then you could have a method to generate an NSString to display it like:
- (NSString*)numberToCurrencyString:(float)num
{
NSString *postfix = #"";
if (num > 1000000000)
{
num = num / 1000000000;
postfix = #" Billion";
}
else if (num > 1000000)
{
num = num / 1000000;
postfix = #" Million";
}
NSString *currencyString = [NSString stringWithFormat:#"%.0f%#", num, postfix];
return currencyString;
}
Note: Your question states that your input needs to remain a string. That's fine. So you'd need to 1.) first parse the number out of the string and 2.) then reconvert it to a string from a number. I've shown how to do step 2 of this process.