Limit a double to two decimal places without trailing zeros - iphone

I read this and that. I want this exactly:
1.4324 => "1.43"
9.4000 => "9.4"
43.000 => "43"
9.4 => "9.40" (wrong)
43.000 => "43.00" (wrong)
In both questions the answers points to NSNumberFormatter. So it should be easy to achieve, but not for me.
- (void)viewDidLoad {
[super viewDidLoad];
UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 100, 200, 20)];
NSNumberFormatter *doubleValueWithMaxTwoDecimalPlaces = [[NSNumberFormatter alloc] init];
[doubleValueWithMaxTwoDecimalPlaces setNumberStyle:NSNumberFormatterDecimalStyle];
[doubleValueWithMaxTwoDecimalPlaces setPaddingPosition:NSNumberFormatterPadAfterSuffix];
[doubleValueWithMaxTwoDecimalPlaces setFormatWidth:2];
NSNumber *myValue = [NSNumber numberWithDouble:0.01234];
//NSNumber *myValue = [NSNumber numberWithDouble:0.1];
myLabel.text = [doubleValueWithMaxTwoDecimalPlaces stringFromNumber:myValue];
[self.view addSubview:myLabel];
[myLabel release];
myLabel = nil;
[doubleValueWithMaxTwoDecimalPlaces release];
doubleValueWithMaxTwoDecimalPlaces = nil;
}
I also tried it with
NSString *resultString = [NSString stringWithFormat: #"%.2lf", [myValue doubleValue]];
NSLog(#"%#", resultString);
So how can I format double values with maximum two decimal places? If the last position contains a zero the zero should be left out.
Solution:
NSNumberFormatter *doubleValueWithMaxTwoDecimalPlaces = [[NSNumberFormatter alloc] init];
[doubleValueWithMaxTwoDecimalPlaces setNumberStyle:NSNumberFormatterDecimalStyle];
[doubleValueWithMaxTwoDecimalPlaces setMaximumFractionDigits:2];
NSNumber *myValue = [NSNumber numberWithDouble:0.01234];
NSLog(#"%#",[doubleValueWithMaxTwoDecimalPlaces stringFromNumber:myValue]];
[doubleValueWithMaxTwoDecimalPlaces release];
doubleValueWithMaxTwoDecimalPlaces = nil;

Try adding the following line, when configuring your formatter:
[doubleValueWithMaxTwoDecimalPlaces setMaximumFractionDigits:2];

NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
[numberFormatter setRoundingMode:NSNumberFormatterRoundDown];
[numberFormatter setMinimumFractionDigits:2];
numberFormatter.positiveFormat = #"0.##";
NSNumber *num = #(total_Value);

How about trimming the unwanted characters from the end of the string?:
NSString* CWDoubleToStringWithMax2Decimals(double d) {
NSString* s = [NSString stringWithFormat:#"%.2f", d];
NSCharacterSet* cs = [NSCharacterSet characterSetWithCharacterInString:#"0."];
NSRange r = [s rangeOfCharacterInSet:cs
options:NSBackwardsSearch | NSAnchoredSearch];
if (r.location != NSNotFound) {
s = [s substringToIndex:r.location];
}
return s;
}

Related

Obj-C How to call a method with return?

I have a method with a return value that I want to call from my MainviewController.m. Also, I must pass a value (float) to the method when calling it.
But I'm having trouble with that, I tried to debug and add some breakpoints and NSLog in the method but it appears that the method is not being called, since the debugger doesn't stop at the breakpoint and doesn't print the NSLog. (the final print (calculatorScreen.text...) just print (null))
MainViewController.m
currentNumber = currentNumber *10 + (float)[sender tag];
NSNumber *convertedNumber = [[NSNumber alloc] init];
NSString *nf = [convertedNumber customFormatNumber:currentNumber];
calculatorScreen.text = [NSString stringWithFormat:#"%#",nf]; // it's printing (null) :(
NSNumber+FormatNumber.h
#interface NSNumber (FormatNumber)
-(NSString *) customFormatNumber:(float)n1;
NSNumber+FormatNumber.m
-(NSString *) customFormatNumber:(float)n1
{
NSLog(#" %f" ,n1); // for debug and a breakpoint here
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setMaximumFractionDigits:2];
[formatter setMinimumFractionDigits:0];
NSString *nf = [formatter stringFromNumber:[NSNumber numberWithFloat:n1]];
NSLog(#"Class %#" ,nf); // for debug
return nf;
}
What am I missing here?
[[NSNumber alloc]init] returns nil because you aren't specifying the number value, and nil targeted actions are ignored.
Let me tell you that you are following a long and unnecessary way, I would just write all this way:
NSNumberFormatter* formatter=[NSNumberFormatter new];
[formatter setMaximumFractionDigits:2];
[formatter setMinimumFractionDigits:0];
formatter.numberStyle= NSNumberFormatterDecimalStyle;
calculatorScreen.text= [formatter stringFromNumber: #(currentNumber*10.0+[sender tag]) ];
Are you trying to overwrite NSNumber?
For CustomNumber.h
#interface CustomNumber:NSNumber
-(NSString *) customFormatNumber:(float) n1;
For CustomNumber.m
-(NSString *) customFormatNumber:(float)n1
{
NSLog(#" %f" ,n1); // for debug and a breakpoint here
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setMaximumFractionDigits:2];
[formatter setMinimumFractionDigits:0];
NSString *nf = [formatter stringFromNumber:[NSNumber numberWithFloat:n1]];
NSLog(#"Class %#" ,nf); // for debug
[formatter release];
return nf;
}
Then in MainViewController.m
currentNumber = currentNumber *10 + (float)[sender tag];
CustomNumber *convertedNumber = [[CustomNumber alloc] init];
calculatorScreen.text = [convertedNumber customFormatNumber:currentNumber];
OR
In MainViewController.m create the method and then the code will be
currentNumber = currentNumber *10 + (float)[sender tag];
calculatorScreen.text = [self customFormatNumber:currentNumber];

how to convert currency in word spell in iphone? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I create the function to convert the Currency to Word Format but my problem is that when put the textfeild value 100000 i need Indian Format one lakh,but it give me one hundred thousand so any solution for that.
NSString *str1 = txtAmount.text;
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle: NSNumberFormatterSpellOutStyle];
NSString *localeStr = [appDel.countryCodeDict valueForKey:appDel.selectedCountry];
if ([appDel.selectedCountry isEqualToString:#"France"]) {
localeStr = #"fr";
}
if ([appDel.selectedCountry isEqualToString:#"Germany"]) {
localeStr = #"de";
}
NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:localeStr];
[formatter setLocale:usLocale];
[formatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
[formatter setNumberStyle:NSNumberFormatterCurrencyStyle];
NSArray *valueArr=[str1 componentsSeparatedByString:#"."];
[formatter setNumberStyle: NSNumberFormatterSpellOutStyle];
NSString *firstStr = [valueArr objectAtIndex:0];
NSString *seconfStr = [valueArr lastObject];
if (valueArr.count==2 && ![seconfStr isEqualToString:#""]) {
double firstAmt = [firstStr doubleValue];
NSString *convertStr = [formatter stringFromNumber:[NSNumber numberWithDouble:firstAmt]];
double secondAmt = [seconfStr doubleValue];
NSString *convertStr1 = [formatter stringFromNumber:[NSNumber numberWithDouble:secondAmt]];
NSString *finalStr = [convertStr stringByAppendingFormat:#" %# %# %#",appDel.firstCurrencystr,convertStr1,appDel.secondCurrencystr];
NSLog(#"%#",finalStr);
NSString *firstCapChar = [[finalStr substringToIndex:1] capitalizedString];
tempStr = [finalStr stringByReplacingCharactersInRange:NSMakeRange(0,1) withString:firstCapChar];
}else{
double firstAmt = [firstStr doubleValue];
NSString *convertStr = [formatter stringFromNumber:[NSNumber numberWithDouble:firstAmt]];
convertStr = [convertStr stringByAppendingFormat:#" %#",appDel.firstCurrencystr];
NSString *firstCapChar = [[convertStr substringToIndex:1] capitalizedString];
tempStr = [convertStr stringByReplacingCharactersInRange:NSMakeRange(0,1) withString:firstCapChar];
}
appDel.lblAmountView.lblAmount.text = tempStr;
Any idea of that.
Dont' know what you have coded but if you want currency to be in indian style check out this code:-
NSLocale *indiaLocale = [[[NSLocale alloc] initWithLocaleIdentifier:#"en_IN"] autorelease];
double currency = 1000000000.00;
NSNumberFormatter *numberFormatter = [[[NSNumberFormatter alloc] init] autorelease];
[numberFormatter setNumberStyle: NSNumberFormatterCurrencyStyle];
[numberFormatter setLocale:indiaLocale];
NSString *numberAsString = [numberFormatter stringFromNumber:[NSNumber numberWithInt:currency]];
NSString *str2 = [NSString stringWithFormat:#"Converted:%#",numberAsString];
NSLog(#"String:%#",str2);
at last i convert the hole currency in lakh and crore format of india:
-(NSString *)stringfromNumberIndia:(NSString *)str_word
{
NSString *tempStr=#"";
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle: NSNumberFormatterSpellOutStyle];
NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_IN"];
[formatter setLocale:usLocale];
[formatter setNumberStyle: NSNumberFormatterSpellOutStyle];
if ([str_word length]>5) {
NSString* str_convert = [str_word substringFromIndex:[str_word length]-5];
NSString* str_convert1 = [str_word substringToIndex:[str_word length]-5];
NSLog(#"str :%#",str_convert);
NSLog(#"str1 :%#",str_convert1);
tempStr = [[self stringfromNumberIndia:str_convert] stringByAppendingString:tempStr];
int l=[str_convert1 length];
for (int i=0; i<l;) {
NSRange range;
if (l>2 && i == 0) {
range=NSMakeRange(l-i-2, 2);
}
else{
range=NSMakeRange(0, l-i);
}
NSString *str_first=[str_convert1 substringWithRange:range];
if ([str_first intValue] == 0) {
if (i == 0)
i+=2;
else
break;
continue;
}
NSLog(#"str_first:%#",str_first);
if (i== 0) {
str_first=[formatter stringFromNumber:[NSNumber numberWithDouble:[str_first doubleValue]]];
str_first = [str_first stringByAppendingFormat:#" lakh "];
tempStr = [str_first stringByAppendingString:tempStr];
}
else {
str_first =[self stringfromNumberIndia:str_first];
str_first = [str_first stringByAppendingFormat:#" crore "];
tempStr = [str_first stringByAppendingString:tempStr];
break;
}
i+=2;
}
}
else if ([str_word intValue] !=0){
double Amt = [str_word doubleValue];
NSString *convertStr = [formatter stringFromNumber:[NSNumber numberWithDouble:Amt]];
NSString *firstCapChar = [convertStr substringToIndex:1];
tempStr = [convertStr stringByReplacingCharactersInRange:NSMakeRange(0,1) withString:firstCapChar];
}
return tempStr;
}
Thanks.

Custom Number Pad with $ sign

Okay so I have a custom number pad that works and shows numbers as 0.00 in a label (numberField), now i need it to show $0.00.
NSString *digit = sender.currentTitle;
numberField.text = [numberField.text stringByAppendingString:digit];
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
[numberFormatter setGroupingSeparator:#""];
[numberFormatter setMaximumIntegerDigits:4];
[numberFormatter setMaximumFractionDigits:2];
[numberFormatter setMaximumFractionDigits:2];
numberField.text = [numberField.text stringByReplacingOccurrencesOfString:#"." withString:#""];
NSDecimalNumber *currency = [[NSDecimalNumber decimalNumberWithString:numberField.text] decimalNumberByDividingBy: [NSDecimalNumber decimalNumberWithString:#"100"]];
NSString *numberFieldFormat = [numberFormatter stringFromNumber:currency];
numberField.text = numberFieldFormat;
I tried a $%1.2f but it crashes because it does not recognize the $ sign as a number.
Can someone help me out here? Or have a better way of making a custom pad with $ sign?
**Edit
I'm considering making numberField a hidden label (alpha 0) and placing a copy (numberField2) directly on top and running it through stringWithFormat. It works but i thought there may be a cleaner way of doing it.
You don't want it to show $0.00. What if I'm in the UK? Wouldn't I then want it to show £0.00?
It looks like you're incorrectly using the NSNumberFormatter. Here's how you format a number for currency:
NSNumberFormatter *f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterCurrencyStyle];
NSString *string = [f stringFromNumber:[NSNumber numberWithFloat:1234.56]];
[f release];
That will format things correctly, regardless of your locale. It'll use the correct currency sign, the correct thousands separator, and the correct decimal separator. Attempting to recreate this functionality yourself is a Bad Idea™.
Try this:
NSString *digit = sender.currentTitle;
numberField.text = [numberField.text stringByAppendingString:digit];
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
[numberFormatter setGrouping Separator:#""];
[numberFormatter setMaximumIntegerDigits:4];
[numberFormatter setMaximumFractionDigits:2];
[numberFormatter setMaximumFractionDigits:2];
numberField.text = [numberField.text stringByReplacingOccurrencesOfString:#"." withString:#""];
numberField.text = [numberField.text stringByReplacingOccurrencesOfString:#"$" withString:#""];
NSDecimalNumber *currency = [[NSDecimalNumber decimalNumberWithString:numberField.text] decimalNumberByDividingBy: [NSDecimalNumber decimalNumberWithString:#"100"]];
NSString *numberFieldFormat = [numberFormatter stringFromNumber:currency];
numberField.text = [NSString stringWithFormat:#"$%#", numberFieldFormat];
From my understanding you just want to append a $ to your string. You could do something like this..
....
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
[numberFormatter setGrouping Separator:#""];
[numberFormatter setMaximumIntegerDigits:4];
[numberFormatter setMaximumFractionDigits:2];
[numberFormatter setMaximumFractionDigits:2];
NSDecimalNumber *currency = [[NSDecimalNumber decimalNumberWithString:numberField.text] decimalNumberByDividingBy: [NSDecimalNumber decimalNumberWithString:#"100"]];
NSString *formatted = [[currency stringValue] stringByReplacingOccurrencesOfString:[currency stringValue] withString:[NSString stringWithFormat:#"$%#",[currency stringValue]]];
NSLog(#"%#", formatted); // Prints $0.00
Or Am I misunderstanding your question?

Format The NSNumber in Objective C

How can I convert NSNumber "1234567 " to "12,34,567"?
I have used the NSNumberFormatter for this,but couldn't get the desired result.
I am doing like this
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
NSString *formattedString = [formatter stringFromNumber:[NSNumber numberWithFloat:1234567]];
NSLog(#":%#",formattedString);
Output: 1,234,567
Desired Output: 12,34,567
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setPositiveFormat:#"##,##,###"];
NSString *formattedNumberString = [numberFormatter
stringFromNumber:[NSNumber numberWithFloat:1234567]];
NSLog(#"formattedNumberString: %#", formattedNumberString);
[numberFormatter release];
NSNumber *number = [NSNumber numberWithInteger:1234567];
NSNumberFormatter *formatter = [NSNumberFormatter new];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
NSLog(#"%#", [formatter stringFromNumber:number]);
[formatter release];

Convert NSNumber to NSString with NSNumberFormatter

I am converting an NSNumber to an NSString assuming in this example that the selected key in "theindex" is 1000000
NSNumber *firstNumber = [tempDict objectForKey:#"theindex"];
NSString *convertNumber = [firstNumber stringValue];
Returning the NSString "1000000"
I would like the string's value to be "1,000,000".
I am not concerned with localization, but understand from other questions that NSNumberFormatter should be implemented. I am not sure how to accomplish this?
Here is an example using a standard formatting style of NSNumberFormatter:
NSNumber *firstNumber = [NSNumber numberWithInt:123456789];
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
NSString *convertNumber = [formatter stringForObjectValue:firstNumber];
NSLog(#"value : %#", convertNumber);
Other examples you can reference at:
http://iosdevelopertips.com/cocoa/formatting-numbers-nsnumberformatter-examples.html
NSNumber *firstNumber = [[NSNumber alloc] initWithInt:1000000] ;
NSNumberFormatter *format=[[NSNumberFormatter alloc] init];
[format setGroupingSize:3];
[format setCurrencyGroupingSeparator:#","];
[format setNumberStyle:NSNumberFormatterDecimalStyle];
NSString *convertNumber = [format stringFromNumber:firstNumber];