Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
Anyone have any idea to show large value in exponent form in objective?
e.g. 10000000000
What will the formula to show this number in exponent form.
This answer assumes you are asking about scientific e-notation.
If your goal is to convert the number 10000000000 to a string as 1e10 then use the e or E format specifier:
NSString *exponent = [NSString stringWithFormat:#"%e", 10000000000];
Use %E is you want a capital E instead of a lowercase e in the output.
And note that %e and %E can be formatted just like %f meaning you can specify the number of decimals, the total width, and whether leading spaces or zeros should be used as needed.
See the full documentation for printf.
Guessing: by "show" you mean convert to text format for display or printing.
If so then the two main ways to produce a textual representation for a numerical value are stringwithFormat: (& friends) and NSNumberFormatter.
The first of these provides a C printf-like facility. For example:
double val = 10000000000;
NSString *text = [NSString stringWithFormat:#"%g", val];
will set text to the string 1e+10. This example uses the %g format, there are others such as %f, and formatting such as the number of decimal places can be specified - for more details see the documentation.
The second provides an object-based facility. For example:
NSNumberFormatter *formatter = [NSNumberFormatter new];
formatter.numberStyle = NSNumberFormatterScientificStyle;
NSString *text = [formatter stringFromNumber:#(val)];
will set text to the string 1E10. There are other properties which can be set to control many aspects of the formatting, and NSNumberFormatter handles international differences in number formatting (like for those countries which use a comma (,) as the decimal fraction indicator rather then the point (.)). Again read the documentation.
HTH
Related
I know the way to set formatted float with specific number
NSLog(#"%.2f", myFloat);
What is the way to set parameter number? Something like this
cell.lblOpenPrice.text = [NSString stringWithFormat:#"%.%if", trade.open_price, trade.digits];
You should use an instance of NSNumberFormatter for this. There are dozens of options, too many to discuss them here. I. e. you can set the total number of digits (significant digits) or the number of integer and fraction digits as discussed here.
NSNumberFormatter *formatter = [NSNumberFormatter new];
// Do the desired configuration
NSString *text = [formatter stringFromNumber:#(myFloat)];
To set a field precision dynamically you use an asterisk in the format and provide the precision argument first, so your code example is:
cell.lblOpenPrice.text = [NSString stringWithFormat:#"%.*f", trade.digits, trade.open_price];
HTH
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I'm quite new to NSString manipulation and don't have much experience at all of manipulating strings in any language really.
My problem is that I have a string that contains a lot of data, within this data is a name that I need to extract into a new NSString. EG:
NSString* dataString =#"randomdata12359123888585/name_john_randomdatawadapoawdk"
"/name_" always precede the data I need and "_" always follows it.
I have looked into things such as NSScanner but I'm not quite sure what the correct approach is or how to implement NSScanner.
Your string format is very well-defined (as you say, the name you are after is always preceded by "/name_" and always followed by "_"), and I suppose that the name ("john") hence cannot contain an underscore.
I'd therefore consider a simple regular expression, which is perfectly suited for this sort of problem:
NSString *regexPattern = #"^.*/name_(.*?)_.*$";
NSString *name = [dataString stringByReplacingOccurrencesOfString: regexPattern
withString: #"$1"
options: NSRegularExpressionSearch
range: NSMakeRange(0, dataString.length)];
In case you are not familiar with regular expressions, what is going on here is:
Begin at the beginning of the string (the "^")
Allow anything (".*") followed by "/name_"
Capture what follows (the parenthesis means "capture this")
In the parenthesis, allow anything (".*"), but make it as short as possible (the "?" after the "*")
It must be followed by an underscore and then allow anything that happens to be there up to the end of the string (the "$")
This will match the whole string, and when substituting the match (i.e., all of the string) with "$1", it will substitute the match with the substring included in the first (and only) parenthesis.
Result: It will produce a string that contains only the name. If the string does not have the correct format (i.e., no name between two underscores), then it will not change anything and return the full, original string.
It is a matter of coding style whether you prefer one approach over the other, but if you like regular expressions, then this approach is both clean, easy to understand and simple to maintain.
As I see it, any fragility in this is due to the data format, which looks suspiciously like something that depends on other "random" pieces of data, so whichever method you choose to parse that string, make sure you add some defensive tests to check the data format and alert you if unexpected strings begin to enter your data. This could be years from now, when you have forgotten everything about underscores, regexes and NSScanner.
-(void)separateString{
NSString* dataString =#"randomdata12359123888585/name_john_randomdatawadapoawdk";
NSArray *arr1 = [dataString componentsSeparatedByString:#"/"];
NSArray *arr2 = [[arr1 objectAtIndex:1] componentsSeparatedByString:#"_"];
NSLog(#"%# %#",arr1,arr2);
}
The output you get is
arr1= (
randomdata12359123888585,
"name_john_randomdatawadapoawdk"
)
arr2 = (
name,
john,
randomdatawadapoawdk
)
now you can access the name or whatever from the array index.
I managed to do this with NSScanner, however the array answer would work too so I've upvoted it.
The NSScanner code I used for anyone else facing a similar problem is:
-(void)formatName{
NSString *stringToSearch = _URLString; //url string is the long string we wish to search.
NSScanner *scanner = [NSScanner scannerWithString:stringToSearch];
[scanner scanUpToString:#"name_" intoString:nil]; // Scan all characters before name_
while(![scanner isAtEnd]) {
NSString *substring = nil;
[scanner scanString:#"name_" intoString:nil]; // Scan the # character
if([scanner scanUpToString:#"_" intoString:&substring]) {
// If the space immediately followed the _, this will be skipped
_nameIwant = substring; //nameIwant is a property to store the name I scanned for
return;
}
}
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Hi I have a problem with strings. I want to add :
NSString *termo = [NSString stringWithFormat:#"%#%#: %# ", #"~00000000:",nazwa, #".*"];
This .* is anything. How can I use it?
Your question is very unclear, however your comment "I have some string which I get from server. I want to parse this string with this" seems to suggest:
that you have a string obtained from somewhere;
this string should contain the text you have stored in the variable nazwa; and
you wish to find the text that follows whatever nazwa contains.
If this guess is correct then the following code fragment might help, it does not contain any checks you need to make to verify the input actually contains what you are looking for and is followed by something - check the documentation for the methods used to see what they return if they don't locate the text etc.:
// a string representing the input
NSString *theInput = #"The quick brown fox";
// nazwa - the text we are looking for
NSString *nazwa = #"quick";
// locate the text in the input
NSRange nazwaPosition = [theInput rangeOfString:nazwa];
// a range contains a location (offset) and a length, so
// adding these finds the offset of what follows
NSUInteger endofNazwa = nazwaPosition.location + nazwaPosition.length;
// extract what follows
NSString *afterNazwa = [theInput substringFromIndex:endofNazwa];
// display
NSLog(#"theInput '%#'\nnazwa '%#'\nafterNazwa '%#'", theInput, nazwa, afterNazwa);
This outputs:
theInput 'The quick brown fox'
nazwa 'quick'
afterNazwa ' brown fox'
HTH
.* is a regular expression that is used to match anything, but if you just want to see if an NSString isn't empty, you're better off doing something like this
![string isEqualToString:#""]
I have a class holding various types of numeric values. Within this class I have a couple of helper methods that are used to output descriptor text for display within my application.
This descriptor text should always appear as an integer or float, depending on the definition of the particular instance.
The class has a property, DecimalWidth, that I use to determine how many decimals to display. I need help writing a line of code that displays the numeric value, but with a fixed number of decimals, (0 is a possibility, and in such a case the value should be displayed as an integer.)
I am aware that I can could return a value like [NSString stringWithFormat:#"%.02f", self.Value] but my problem is that I need to replace the '2' in the format string with the value of DecimalWidth.
I can think of couple ways of solving this problem. I could concat a string together and that is as the format string for the outputted string line. Or, I could make a format string within a format string.
These solutions sound hideous and seem rather inefficient, but maybe these are the best options that I have.
Is there an elegant way of constructing a dynamic formatting string where the output is a fixed decimal width number but the specified decimal width is dynamic?
That doesn't sound hideous or inefficient to me.
[NSString stringWithFormat:[NSString stringWithFormat:#"%%.%df", DecimalWidth], self.Value]
In fact I think it is rather elegant.
However one solution for the problem is definitely question suggested by #lulius caesar,
But one good way is also using NSNumberFormatter. Below is a sample code you can use to generate decimal values with fixed decimal number
NSNumberFormatter *numberFormatter=[[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
[numberFormatter setMinimumFractionDigits:DecimalWidth];
[numberFormatter setMaximumFractionDigits:DecimalWidth];
NSString * decimalString = [numberFormatter stringFromNumber:[NSNumber numberWithFloat:self.value]]]
I am trying to generate a numerical string by padding the number with zeroes to the left.
0 would become 00000
1 would become 00001
10 would become 00010
I want to create five character NSString by padding the number with zeroes.
I read this Create NSString by repeating another string a given number of times but the output is an NSMutableString.
How can I implement this algorithm with the output as an NSString?
Best regards.
You can accomplish this by calling
[NSString stringWithFormat:#"%05d", [theNumber intValue]];
where theNumber is the NSString containing the number you want to format.
For further reading, you may want to look at Apple's string formatting guide or the Wikipedia entry for printf.
One quick & simple way to do it:
unsigned int num = 10; // example value
NSString *immutable = [NSString stringWithFormat:#"%.5u", num];
If you actually really want to use the long-winded approach from the example you read, you can send a “copy” message to a mutable string to get an immutable copy. This holds for all mutable types.