how to remove excess 0 before the decimal point - ios

I followed this solution (http://davidjhinson.wordpress.com/2008/12/22/simple-formatting-in-a-cocoa-touch-text-edit-field-uitextfield/) and it works fine when I enter the first digit [result: "0.01"]. But when I enter the second digit the result is like this "00.11". It is adding another 0. How can make it to format my textfield into this "0.11" when I enter the second digit.
Here's my code
stringToFormat = [stringToFormat stringReplacingOccurenceOfString:[NSString stringWithFormat:#"%#", [GLobalSettings getCurrency]] withString #""]; // remove currency
NSString normalizedString = stringToFormat;
normalizedString = [normalizedString stringByReplacingOccurenceOfString"#"." withString:#""]; // remove dot
if(normalizedString.length <= 2)
{
normalizedString = [#"" stringByAppendingFormat:#"%.2f", [normalizedString floatValue]/100.0];
return [NSString stringWithFormat:#"%# %#", [GlobalSettings getCurrency], normalizedString];
}
any help would be much appreciated...thanks..

Related

Get one digit after decimal point iOS Objective C

I am trying to get one digit after decimal and store it as double.
For eg : -
float A = 146.908295;
NSString * string = [NSString stringWithFormat:#"%0.01f",A]; // op 146.9
double B = [string doubleValue]; // op 146.900000
i want output as 146.9 in double or float form..,before duplicating or downvoting make sure the answer to this output is given..
Thanks
Edited:-
NSString * str = [NSString stringWithFormat:#"%0.01f",currentAngle];
tempCurrentAngle = [str doubleValue];;
tempCurrentAngle = tempCurrentAngle - 135.0;
if (tempCurrentAngle == 8.7) {
NSLog(#"DONE ");
}
here currentAngle is coming from continueTrackingWithTouch method, which will be in float..here it does not enter in if loop even when tempCurrentAngle value changes to 8.700000 .
You can compare string values instead of double like,
double currentAngle = 143.7; // I have taken static values for demo.
double tempCurrentAngle = 0.0;
NSString * str = [NSString stringWithFormat:#"%0.01f",currentAngle];
tempCurrentAngle = [str doubleValue];;
tempCurrentAngle = tempCurrentAngle - 135.0;
NSString *strToCompare = [NSString stringWithFormat:#"%0.01f",tempCurrentAngle];
if ([strToCompare isEqualToString:#"8.7"] ) {
NSLog(#"DONE ");
}
If you debug once line by line then you will get idea that why it was not entering in if caluse.
tempCurrentAngle get 143.69999999999999 when you convert str to double then you reduce 135.0 from it so it's value will be 8.6999999999999886 and then you compare it with 8.7 then it will definitely not being equal! but if you convert tempCurrentAngle string with one decimal point then it will be 8.7! so you should compare string values instead of double!

getting certain portion of nsstring

I have string as follows in objective c
NSString *str = #"access_token=E2JmCPLtVySGn-cGGJGGnQ&email=abc#gmail.com";
How can i get only E2JmCPLtVySGn-cGGJGGnQ ?
You can use a Regular Expression (RegEx) to find character patterns.
The pattern matching syntax can be found in the ICU User Guide Regular Expressions
In the example the pattern is: find the first "=" and all characters up to but not including the character "&". In the pattern '(?<=access_token=)" is a look-behind assertion meaning that the "access_token=" must precede the matched text, "[^&]+" the brackets the "[]" mean a character class, the "^" al but the following character, the "+" means one or more.
NSString *str = #"access_token=E2JmCPLtVySGn-cGGJGGnQ&email=abc#gmail.com";
NSString *regexPattern = #"(?<=access_token=)[^&]+";
NSString *found = nil;
NSRange range = [str rangeOfString:regexPattern options:NSRegularExpressionSearch];
if (range.location != NSNotFound) {
found = [str substringWithRange:range];
}
NSLog(#"Range: %#", NSStringFromRange(range));
NSLog(#"found: %#", found);
NSLog output if found:
Range: {13, 22}
found: E2JmCPLtVySGn-cGGJGGnQ
There is a method of the NSString class called rangeOfString: that returns an NSRange struct. If you know that your returned value always has the text access_token= and also includes &email and the format is always the same, you can use this rangeOfString: method to sniff out the token.
NSRange accessTokenRange = [str rangeOfString:#"access_token="];
//this would return (0,13) for index:0, length: 13
NSRange emailRange = [str rangeOfString:#"&email="];
//this would return (34,7)
NSInteger tokenLength = ( emailRange.location + 1 ) - accessTokenRange.length;
//the point where &email begins is at index 34, but it starts at 0
//so it's actually the 35th character
//the access_token= string is 13 characters long, so 35-13 = 22
//so you know that the actual token value is 22 characters long
NSRange trueTokenRange = NSMakeRange(accessTokenRange.length,tokenLength);
NSString *tokenSubstring = [str substringWithRange:trueTokenRange];
I don't think my math is off, zero indexing can introduce off by 1 errors if you're not careful, I usually have NSLog going on each range so I can double check where I need to add or subtract 1. But essentially you'll be starting at the 14th character, which is index 13 of the string, and reading the next 22 characters.

Check to see if UITextField has a numeric value greater than 0

I have a UITextField and I only want a number greater than 0 ( I don't want non-numeric characters or the value 0 )
This is how I check to see if it is empty:
if(seizure.text.length==0)
This is how I check to see if it is equal to 0:
else if(seizure.text doubleValue]==0)
How can I check for non-numeric characters?
First check to see if you have any characters in the string, then check to make sure that it only contains numeric characters, and finally check to see if the value is greater than 0:
if (seizure.text.length > 0)
{
NSCharacterSet *nonNumbers = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
if ([seizure.text rangeOfCharacterFromSet:nonNumbers].location == NSNotFound)
{
if ([seizure.text doubleValue] > 0)
{
// Text Field contains a numeric value greater than 0
NSLog(#"Good number.");
return;
}
}
}
// If we make it to here, it does not meet your requirements.
NSLog(#"Bad Number.");
NSScanner will do the job nicely here. Unlike -[NSString doubleValue], its scanDouble: can parse and then also tell you whether it consumed the entire string, so you will know that there are non-numerical characters present.
Demonstration on some test cases. See the comments for descriptions of the expected results.
NSArray * texts = #[// First four unacceptable because non-numeric
#"", #"Hello, world!", #"1.0 excelsior", #"Jiminy 1.0 Crickets",
// These three unacceptable because 0 or less
#"0.0" #"0", #"-2048",
// Last three are good
#"3.14159", #"1", #"10000000000.0"];
for( NSString * text in texts ){
NSScanner * scanner = [NSScanner scannerWithString:text];
double val;
[scanner scanDouble:&val];
// Scanned the whole string and ended up with a positive value
if( [scanner isAtEnd] && val > 0 ){
NSLog(#"'%#'? I accept.", text);
}
else {
NSLog(#"'%#' is no good.", text);
}
}
[seizure.text doubleValue] == 0 will be true either if seizure.text is a textual representation of zero or if it doesn't contain a valid textual representation of a number (see the documentation for doubleValue).
In other words if this expression is false then you have a string value which starts with a number. However you still don't know if you string value contains only a number, e.g. [#"2.5 miles" doubleValue] has the value 2.5. If you need to handle strings like this you should look at NSScanner.

NSString floatValue seems to not be operating correctly

I have a text field in an xib file. In a method in the .m file, I can print the contents of the text field, but I cannot get those contents converted to a float. The text field is formatted with commas, as in 123,456,789. Below is the code snippet, where datacellR2C2 is the textfield.
float originalValue2 = originalValue2 = [datacellR2C2.text floatValue];
NSLog(#"datacellR2C2 as text --> %# <---\n",datacellR2C2.text); // this correctly shows the value in datacellR2C2
NSLog(#"originalValue2 = %f <--\n", originalValue2); // this incorrectly returns the value 1.0
I would appreciate any suggestions for a fix or a direction where I should look for the problem.
In the declaration for -floatValue a comment is shown:
/* The following convenience methods all skip initial space characters
(whitespaceSet) and ignore trailing characters. NSScanner can be used
for more "exact" parsing of numbers.
*/
Ergo, commas cause truncation, because they are trailing chars. Even the string you provided (123,456,789) only prints 123.000, because that's all -floatValue sees.
//test
NSString *string = #"123,456,789";
float originalValue2 = [string floatValue];
NSLog(#"datacellR2C2 as text --> %# <---\n",string); // this correctly shows the value in datacellR2C2
NSLog(#"originalValue2 = %f <--\n", originalValue2);
//log
2012-07-07 22:16:15.913 [5709:19d03] datacellR2C2 as text --> 123,456,789 <---
2012-07-07 22:16:15.916 [5709:19d03] originalValue2 = 123.000000 <--
Just get rid of them with a simple +stringByReplacingOccurrencesOfString:withString:, and remove those trailing commas:
//test
NSString *string = #"123,456,789";
NSString *cleanString = [string stringByReplacingOccurrencesOfString:#"," withString:#""];
float originalValue2 = [cleanString floatValue];
NSLog(#"datacellR2C2 as text --> %# <---\n",cleanString); // this correctly shows the value in datacellR2C2
NSLog(#"originalValue2 = %f <--\n", originalValue2);
//log
2012-07-07 22:20:20.737 [5887:19d03] datacellR2C2 as text --> 123456789 <---
2012-07-07 22:20:20.739 [5887:19d03] originalValue2 = 123456792.000000 <--
By the way, a float is rounding that string up to an even number, use double precision instead.

How to make first letter uppercase in a UILabel?

I'm developing an iPhone app. In a label, I want to show an user's first letter of the name uppercase. How do I do that?
If there is only one word String, then use the method
-capitalized
let capitalizedString = myStr.capitalized // capitalizes every word
Otherwise, for multi word strings, you have to extract first character and make only that character upper case.
(2014-07-24: Currently accepted answer is not correct) The question is very specific: Make the first letter uppercase, leave the rest lowercase. Using capitalizedString produces a different result: “Capitalized String” instead of “Capitalized string”. There is another variant depending on the locale, which is capitalizedStringWithLocale, but it's not correct for spanish, right now it's using the same rules as in english, so this is how I'm doing it for spanish:
NSString *abc = #"this is test";
abc = [NSString stringWithFormat:#"%#%#",[[abc substringToIndex:1] uppercaseString],[abc substringFromIndex:1] ];
NSLog(#"abc = %#",abc);
In case someone is still interested in 2016, here is a Swift 3 extension:
extension String {
func capitalizedFirst() -> String {
let first = self[self.startIndex ..< self.index(startIndex, offsetBy: 1)]
let rest = self[self.index(startIndex, offsetBy: 1) ..< self.endIndex]
return first.uppercased() + rest.lowercased()
}
func capitalizedFirst(with: Locale?) -> String {
let first = self[self.startIndex ..< self.index(startIndex, offsetBy: 1)]
let rest = self[self.index(startIndex, offsetBy: 1) ..< self.endIndex]
return first.uppercased(with: with) + rest.lowercased(with: with)
}
}
Then you use it exactly as you would for the usual uppercased() or capitalized():
myString.capitalizedFirst() or myString.capitalizedFirst(with: Locale.current)
Simply
- (NSString *)capitalizeFirstLetterOnlyOfString:(NSString *)string{
NSMutableString *result = [string lowercaseString].mutableCopy;
[result replaceCharactersInRange:NSMakeRange(0, 1) withString:[[result substringToIndex:1] capitalizedString]];
return result;
}
This is for your NSString+Util category...
- (NSString *) capitalizedFirstLetter {
NSString *retVal;
if (self.length < 2) {
retVal = self.capitalizedString;
} else {
retVal = string(#"%#%#",[[self substringToIndex:1] uppercaseString],[self substringFromIndex:1]);
}
return retVal;
}
You can do that with NSString stringWithFormat, of course. I use this weirdness:
#define string(...) \
[NSString stringWithFormat:__VA_ARGS__]
As an extension to the accepted answer
capitalizedString is used for making uppercase letters .
NSString *capitalizedString = [myStr capitalizedString]; // capitalizes every word
But if you have many words in a string and wants to get only first character as upper case use the below solution
NSString *firstCapitalChar = [[string substringToIndex:1] capitalizedString];
NSString *capString = [string stringByReplacingCharactersInRange:NSMakeRange(0,1) withString: capString];
// extract first character and make only that character upper case.
here's a swift extension for it
extension NSString {
func capitalizeFirstLetter() -> NSString {
return self.length > 1 ?
self.substringToIndex(1).capitalizedString + self.substringFromIndex(1) :
self.capitalizedString
}
}
This is how it worked for me:
NSString *serverString = jsonObject[#"info"];
NSMutableString *textToDisplay = [NSMutableString stringWithFormat:#"%#", serverString];
[textToDisplay replaceCharactersInRange:NSMakeRange(0, 1) withString:[textToDisplay substringToIndex:1].capitalizedString];
cell.infoLabel.text = textToDisplay;
Hope it helps.
Swift:
let userName = "hard CODE"
yourLabel.text = userName.localizedUppercaseString
I recommend using this localised version of uppercase, since names are locale sensitive.

Resources