Float to string (removing trailing zeros) [duplicate] - ios

This question already has answers here:
How do I change the number of decimal places iOS?
(5 answers)
Closed 9 years ago.
Can anyone help me with converting float to string?
if I use [NSString stringWithFormat:#"%f", f] I will get something like:
1.0300000
1.0000000
1.0471000
if I use [NSString stringWithFormat:#"%.2f", f] I will get rounded values like:
1.03
1.00
1.05
but I need
1.03
1
1.0471
please help!

Use NSNumberFormatter instead and set maximumFractionDigits.
http://developer.apple.com/library/ios/ipad/#documentation/cocoa/Conceptual/DataFormatting/Articles/dfNumberFormatting10_4.html
http://developer.apple.com/library/ios/ipad/#documentation/cocoa/Reference/Foundation/Classes/NSNumberFormatter_Class/Reference/Reference.html%23//apple_ref/occ/instm/NSNumberFormatter/setMaximumFractionDigits:

try this code for your project
- (NSString *) floatToString:(float) val {
NSString *ret = [NSString stringWithFormat:#\"%.5f\", val];
unichar c = [ret characterAtIndex:[ret length] - 1];
while (c == 48 || c == 46) { // 0 or .
ret = [ret substringToIndex:[ret length] - 1];
c = [ret characterAtIndex:[ret length] - 1];
}
return ret;
}

Related

Concatenate a NSInteger to NSInteger

i'm making my own calculator and i came to the question.
Sorry for newbie question , but I didn't find it.
How can i append a NSInteger to another NSInteger in Objective-C;
for example:
5 + 5 = 55
6 + 4 + 3 = 643
etc.
You have to convert them to strings. Here's one way:
NSNumber *i1 = #6;
NSNumber *i2 = #4;
NSNumber *i3 = #3;
NSMutableString *str = [NSMutableString new];
[str appendString:[i1 stringValue]];
[str appendString:[i2 stringValue]];
[str appendString:[i3 stringValue]];
NSLog(#"result='%#", str);
However, having said all that, it's not clear to me why you are concatenating at all.
If they are a single digit (as in a calculator) you can simply do:
NSInteger newNumber = (oldNumber * 10) + newDigit;
or in a method:
- (NSInteger)number:(NSInteger)currentNumber byAdding:(NSInteger)newDigit {
//Assumes 0 <= newDigit <= 9
return (currentNumber * 10) + newDigit;
}
If they have more than one digit you can make them into strings, concatenate them and convert back to integers or use simple arithmetic to find out the power of 10 you must multiply by.
EDIT: 6 + 4 + 3 Assuming a digit is provided at a time:
NSInteger result = [self number:[self number:6 byAdding:4] byAdding:3];
Purely arithmetic solution:
- (NSInteger)powerOfTenForNumber:(NSInteger)number {
NSInteger result = 1;
while (number > 0) {
result *= 10;
number /= 10;
}
return result;
}
- (NSInteger)number:(NSInteger)currentNumber byAdding:(NSInteger) newNumber {
return (currentNumber * [self powerOfTenForNumber:newNumber]) + newNumber;
}

How to display hyphen in uilabel?

How to display hyphen with UILabel like this, - A I origine - , Here I use the string appending method. I get this type of output - À l'origine de la guerre -. But I want display hyphen before the starting point of text and display hyphen after 10 charatcers.
I was searched but i can't get valied source. kindly give any suggestion if you know.
NSString *tempStr = #" - ";
tempStr = [tempStr stringByAppendingString:NSLocalizedString(#"OriginallyWar", #"")];
tempStr = [tempStr stringByAppendingString:#" -"];
[headingLabel setText:tempStr];
[headingLabel setFont:MRSEAVES_BOLD(17)];
Use NSMutableString and insert characters,
[yourString insertString:#"-" atIndex:10];
if you are using StoryBoard directly set it to the text property on Attribute inspector. Put 10 empty spaces after the end of character and the -.
You may try this code
NSString *inputString = #"OriginallyWarDFdfsdfdDFSDfdsfdsfDFdsfadsfawerdsaf";
NSMutableString *localizedInputString = [NSMutableString stringWithString:NSLocalizedString(inputString, #"")];
int numberOfCharacters = localizedInputString.length;
int numberOf10s = (numberOfCharacters/10 + 1);
int numberOfCharactersToBeInserted = 0;
for (int i = 1; i < numberOf10s; i++) {
int characterIndex = (i * 10) + numberOfCharactersToBeInserted;
if (i == (numberOf10s - 1) && numberOfCharacters % 10 == 0) {
[localizedInputString insertString:#" -" atIndex:characterIndex];
numberOfCharactersToBeInserted = 2 * i;
} else {
[localizedInputString insertString:#" - " atIndex:characterIndex];
numberOfCharactersToBeInserted = 3 * i;
}
}
if (numberOfCharacters == 0) {
[localizedInputString insertString:#"-" atIndex:0];
} else {
[localizedInputString insertString:#"- " atIndex:0];
}
NSLog(#"localizedInputString : %#", localizedInputString);
try using NSMutableString
NSString *tempStr = #" - ";
tempStr = [tempStr stringByAppendingString:NSLocalizedString(#"OriginallyWar", #"")];
NSMutableString *tempStrMutable=[[NSMutableString alloc]initWithString:tempStr];
[tempStrMutable insertString:#"-" atIndex:10];
[headingLabel setText:tempStrMutable];

How to merge 2 NSStrings with a formatter?

Merging these two strings:
#"###.##"
#"123"
Should output:
#"1.23"
I have developed a solution for this, but I'm looking for a simpler way, Using a NSNumberFormater, or some other API that I might be missing in Apple's documentation.
Thank you!
-
The solution as is right now, that I'm trying to get rid of:
/**
* User inputs a pure, non fractional, numeric string (e.g 1234) We'll see how many fraction digits it needs and format accordingly (e.g. 1234 produces a string such as '12.34' for 2 fractional digits. 12 will produce '0.12'.)
*
* #return The converted numeric string in an instance of NSDecimalNumber
*/
- (NSDecimalNumber *)decimalNumberFromRateInput
{
if (_numericInput == nil ||
_numericInput.length == 0) {
_numericInput = #"0";
}
[self clearLeadingZeros];
if (self.formatter == nil) {
return nil;
}
if (self.formatter.maximumFractionDigits == 0) {
return [NSDecimalNumber decimalNumberWithString:_numericInput];
}
else if (_numericInput.length <= self.formatter.maximumFractionDigits) {
NSString *zeros = #"";
for (NSInteger i = _numericInput.length; i < self.formatter.maximumFractionDigits ; i++) {
zeros = [zeros stringByAppendingString:#"0"];
}
NSString *decimalString = [NSString stringWithFormat:#"0.%#%#",zeros,_numericInput];
return [NSDecimalNumber decimalNumberWithString:decimalString];
}
else {
NSString *decimalPart = [_numericInput substringToIndex: _numericInput.length - self.formatter.maximumFractionDigits];
NSString *fractionalPart = [_numericInput substringFromIndex:_numericInput.length - self.formatter.maximumFractionDigits];
NSString *decimalString = [NSString stringWithFormat:#"%#.%#", decimalPart, fractionalPart];
return [NSDecimalNumber decimalNumberWithString: decimalString];
}
}
If I understand your goal correctly, the solution should be much simpler:
float number = [originalString floatValue] / 100.0;
NSString *formattedString = [NSString stringWithFormat:#"%.2f", number];

NSString is a number? [duplicate]

This question already has answers here:
Check that a input to UITextField is numeric only
(22 answers)
Closed 8 years ago.
I have a TextField and wanted to know if the user just pressed numbers
eg::
_tfNumber.text only has numbers?
is there any function on NSString for this?
This will let you know if all of the characters are numbers:
NSString *originalString = #"1234";
NSCharacterSet *numberSet = [NSCharacterSet decimalDigitCharacterSet];
NSString * trimmedString = [originalString stringByTrimmingCharactersInSet:numberSet];
if ((trimmedString.length == 0) && (originalString.length > 0)) {
NSLog(#"Original string was all numbers.");
}
Note that this ensures it won't give a false positive for the empty string, which technically also doesn't contain any non-numbers.
try this:
NSCharacterSet *_NumericOnly = [NSCharacterSet decimalDigitCharacterSet];
NSCharacterSet *myStringSet = [NSCharacterSet characterSetWithCharactersInString:mystring];
if ([_NumericOnly isSupersetOfSet: myStringSet]) {
NSLog(#"String has only numbers");
}
I got it from: http://i-software-developers.com/2013/07/01/check-if-nsstring-contains-only-numbers/
You can use this method in your UITextField's delegate method textField:shouldChangeCharactersInRange:replacementString: and do the verification while the user is typing.
No, but it should be easy to write:
- (BOOL)justContainsNumbers:(NSString *)str {
if ([str length] == 0)
return NO;
for (NSUInteger i = 0; i < [str length]; i++)
if (!isdigit([str characterAtIndex:i]))
return NO;
return YES;
}
Let's try regular Expression,
NSString * numberReg = #"[0-9]";
NSPredicate * numberCheck = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", numberReg];
if ([numberCheck evaluateWithObject:textField.text])
NSLog (#"Number");
No. NSString is not an NSNumber and any values you get from a UITextField will be an NSString. See THIS SO answer for converting that entered NSString value into an NSNumber.

How to calculate number of digits after floating point in iOS?

How can I calculate the number of digits after the floating point in iOS?
For example:
3.105 should return 3
3.0 should return 0
2.2 should return 1
Update:
Also we need to add the following example. As I want to know number of digits in the fraction part.
1e-1 should return 1
Try this way:
NSString *enteredValue=#"99.1234";
NSArray *array=[enteredValue componentsSeparatedByString:#"."];
NSLog(#"->Count : %ld",[array[1] length]);
What I used is the following:
NSString *priorityString = [[NSNumber numberWithFloat:self.priority] stringValue];
NSRange range = [priorityString rangeOfString:#"."];
int digits;
if (range.location != NSNotFound) {
priorityString = [priorityString substringFromIndex:range.location + 1];
digits = [priorityString length];
} else {
range = [priorityString rangeOfString:#"e-"];
if (range.location != NSNotFound) {
priorityString = [priorityString substringFromIndex:range.location + 2];
digits = [priorityString intValue];
} else {
digits = 0;
}
}
Maybe there is a more elegant way to do this, but when converting from a 32 bit architecture app to a 64 bit architecture, many of the other ways I found lost precision and messed things up. So here's how I do it:
bool didHitDot = false;
int numDecimals = 0;
NSString *doubleAsString = [doubleNumber stringValue];
for (NSInteger charIdx=0; charIdx < doubleAsString.length; charIdx++){
if ([doubleAsString characterAtIndex:charIdx] == '.'){
didHitDot = true;
}
if (didHitDot){
numDecimals++;
}
}
//numDecimals now has the right value

Resources