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

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.

Related

Information not being received from server?

Okay, my problem is very simple. Below is my code that is receiving prices from an API, in my code I want the today current price to be displayed, yesterdays price, and the change in percent from yesterday to today. Unfortunately, only the current price is showing properly, but the yesterday and the percent change just show N/A.
Any help is appreciated!
if (refreshing) return;
refreshing = YES;
UIApplication* app = [UIApplication sharedApplication];
app.networkActivityIndicatorVisible = YES;
//self.priceLabel.text = #"Loading...";
//self.yesterdayLabel.text = #"Loading...";
//self.changeLabel.text = #"Loading...";
[NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:#"https://coinbase.com/api/v1/prices/spot_rate"]] queue:[NSOperationQueue mainQueue] completionHandler:^ (NSURLResponse *req, NSData *recv, NSError *err) {
if (err) {
// report
[self setCurrentPrice:#"N/A"];
refreshing = NO;
return;
}
NSError *newError = nil;
NSDictionary *serial = [NSJSONSerialization JSONObjectWithData:recv options:0 error:&newError];
if (newError) {
// report
[self setCurrentPrice:#"N/A"];
refreshing = NO;
return;
}
NSString *amount = [serial objectForKey:#"amount"];
NSString *price = [NSString stringWithFormat:#"%# %#", amount, [serial objectForKey:#"currency"]];
[self setCurrentPrice:[NSString stringWithFormat:#"%#", price]];
// maybe setup a better method.
float diff = [yesterdaysPrice floatValue];
if (diff == 0.0)
self.differenceInPrices = #"N/A";
else {
float amt = [amount floatValue];
float percentChange = amt/diff;
if ((diff == 0) || (amt == diff))
percentChange = 0.00;
percentChange *= 100.00;
self.differenceInPrices = [NSString stringWithFormat:#"%f%%", percentChange];
}
NSMutableDictionary *saveState = [[[NSUserDefaults standardUserDefaults] objectForKey:#"save"] mutableCopy];
[saveState setObject:price forKey:#"price"];
[saveState setObject:yesterdaysPrice forKey:#"lastCheckedPrice"];
NSDateComponents *compon = [[NSCalendar currentCalendar] components:(NSUndefinedDateComponent) fromDate:[NSDate date]];
[saveState setObject:[NSString stringWithFormat:#"%ld", (usingYesterdaysPrices ? [[saveState objectForKey:#"day"] intValue] : [compon day])] forKey:#"day"];
[[NSUserDefaults standardUserDefaults] setObject:saveState forKey:#"save"];
[[NSUserDefaults standardUserDefaults] synchronize];
self.priceLabel.text =self.currentPrice;
self.yesterdayLabel.text = [NSString stringWithFormat:#"%#", yesterdaysPrice];
self.changeLabel.text = differenceInPrices;
app.networkActivityIndicatorVisible = NO;
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"MM/dd/yyyy"];
NSDateFormatter *timeFormat = [[NSDateFormatter alloc] init];
[timeFormat setDateFormat:#"h:mm:ss aa"];
NSDate *now = [[NSDate alloc] init];
NSString *theDate = [dateFormat stringFromDate:now];
NSString *theTime = [timeFormat stringFromDate:now];
lstUpdate.text = [NSString stringWithFormat:#"Updated: %# at %#", theDate, theTime];
refreshing = NO;
}];
I also have this code in my viewDidLoad,
[super viewDidLoad];
refreshing = NO;
NSDictionary *save = [[NSUserDefaults standardUserDefaults] objectForKey:#"save"];
if (save) {
int timeStamp = [[save objectForKey:#"day"] intValue];
NSDateComponents *compon = [[NSCalendar currentCalendar] components:(NSUndefinedDateComponent) fromDate:[NSDate date]];
if ([compon day] != timeStamp) {
usingYesterdaysPrices = YES;
yesterdaysPrice = [save objectForKey:#"lastCheckedPrice"];
if (!yesterdaysPrice) {
yesterdaysPrice = #"N/A";
}
}
}
else {
yesterdaysPrice = #"N/A";
}
self.differenceInPrices = #"N/A";
[self sendNewRequest:nil];
[NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:#selector(sendNewRequest:) userInfo:Nil repeats:YES];

Currency Formatter for different Locale in iOS

I want to convert this String: 1000000 to following format: 10,00,000 but, I am getting output like this : 1,000,000 which is wrong. I need 10,00,000.
My Code :
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
inputnumber = newString;
NSNumberFormatter* formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterCurrencyStyle];
[formatter setCurrencySymbol:#""];
[formatter setMaximumFractionDigits:2];
[formatter setMinimumFractionDigits:2];
[formatter setUsesGroupingSeparator:YES];
[formatter setCurrencyGroupingSeparator:#","];
// [formatter setCurrencyDecimalSeparator:#"."];
[formatter setGroupingSeparator:#","];
NSNumber *num = [NSNumber numberWithDouble:[inputnumber doubleValue]];
inputnumber = [formatter stringFromNumber:num];
It's an Indian Currency Format. So, you have to set #"en_IN" as currencyFormatter Locale.
Working Code :
NSNumberFormatter *currencyFormatter = [[NSNumberFormatter alloc] init];
[currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
[currencyFormatter setCurrencySymbol:#""];
[currencyFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:#"en_IN"] autorelease]];
NSLog(#"Final Value :: %#", [currencyFormatter stringFromNumber:[NSNumber numberWithFloat:1000000]]);
For Swift check this:
let initalValue:NSString = "1000000"
let currencyFormatter = NSNumberFormatter()
currencyFormatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle
currencyFormatter.locale = NSLocale (localeIdentifier: "en_IN")
let formattedValue = currencyFormatter.stringFromNumber(initalValue.doubleValue)
print(formattedValue)

How to compare curent time lie between two time slot

I hava an array of NSDictionary like this.
{
id = 12;
"time_from" = "12:00";
"time_to" = "16:00";
"timing_name" = Lunch;
},
{
id = 11;
"time_from" = "08:00";
"time_to" = "12:00";
"timing_name" = BreakFast;
},
{
id = 13;
"time_from" = "09:00";
"time_to" = "10:00";
"timing_name" = Dinner;
}
Suppose my current time is 8:45 then how can we find exact dictionary using predicate if current time exit between time_from and time_to.
Actully i need a predicate.
You can try this,
NSMutableArray *testArray = [NSMutableArray array];
NSMutableDictionary *testDict = [NSMutableDictionary dictionary];
[testDict setObject:#"12:45" forKey:#"time-from"];
[testDict setObject:#"14:45" forKey:#"time-to"];
[testArray addObject:testDict];
NSPredicate *timePredicate = [NSPredicate predicateWithBlock:^BOOL(NSMutableDictionary *dict, NSDictionary *bindings) {
NSString *timeFromString = [dict objectForKey:#"time-from"];
NSString *timeToString = [dict objectForKey:#"time-from"];
// find minutes from 00-0
//get current time minutes from 00-00
return (currentTimeMinutes>startimeMinutes) && (currentTimeMinutes<=endtimeMinutes)
}];
[testArray filterUsingPredicate:timePredicate];
-(void)makeCalculation
{
NSMutableDictionary *temp=[[NSMutableDictionary alloc]init];
[temp setObject:#"13" forKey:#"id"];
[temp setObject:#"12:00" forKey:#"timeFrom"];
[temp setObject:#"16:00" forKey:#"timeTo"];
NSMutableDictionary *temp1=[[NSMutableDictionary alloc]init];
[temp1 setObject:#"13" forKey:#"id"];
[temp1 setObject:#"08:00" forKey:#"timeFrom"];
[temp1 setObject:#"12:00" forKey:#"timeTo"];
NSMutableDictionary *temp2=[[NSMutableDictionary alloc]init];
[temp2 setObject:#"13" forKey:#"id"];
[temp2 setObject:#"09:00" forKey:#"timeFrom"];
[temp2 setObject:#"10:00" forKey:#"timeTo"];
NSMutableArray *arrayOfDict=[[NSMutableArray alloc]init];
[arrayOfDict addObject:temp];
[arrayOfDict addObject:temp1];
[arrayOfDict addObject:temp2];
NSMutableArray *timeToCompare=[[NSMutableArray alloc]initWithObjects:#"8:45",#"8:45", nil];
for(int k=0;k<[arrayOfDict count];k++)
{
NSMutableDictionary *temp=[arrayOfDict objectAtIndex:k];
NSString *timeFrom=[temp objectForKey:#"timeFrom"];
NSString *timeTo=[temp objectForKey:#"timeTo"];
NSMutableArray *tempTocheck=[[NSMutableArray alloc]initWithObjects:timeFrom,timeTo, nil];
if([self isTimeClash:timeToCompare compareWith:tempTocheck])
{
NSLog(#"Time Belong in id:%#",[temp objectForKey:#"id"]);
}
}
}
-(BOOL)isTimeClash:(NSMutableArray *)timeToCheck compareWith:(NSMutableArray *)timeToCompare
{
int Start1=[self getMinitesFromTime:[timeToCheck objectAtIndex:0]];
int end1=[self getMinitesFromTime:[timeToCheck objectAtIndex:1]];
int start2=[self getMinitesFromTime:[timeToCompare objectAtIndex:0]];
int end2=[self getMinitesFromTime:[timeToCompare objectAtIndex:1]];
if(start2>=end1 || end2<=Start1)
{
NSLog(#"Clash not happeed");
return NO;
}
else
{
NSLog(#"clash hapens ");
return YES;
}
}
-(int)getMinitesFromTime:(NSString *)timeINHours
{
NSInteger hrVal1 = [(timeINHours) intValue] ;
NSArray *array1 = [timeINHours componentsSeparatedByString:#":"];
int minVal1 = [[array1 lastObject]intValue];
hrVal1 = hrVal1 *60;
minVal1 = hrVal1 + minVal1;
return minVal1;
}
Try to use this one...
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:[NSDate date]];
NSInteger currHr = [components hour];
NSInteger currtMin = [components minute];
NSString *startTime = #"10:00";
NSString *endTime = #"16:00";
int stHr = [[[startTime componentsSeparatedByString:#":"] objectAtIndex:0] intValue];
int stMin = [[[startTime componentsSeparatedByString:#":"] objectAtIndex:1] intValue];
int enHr = [[[endTime componentsSeparatedByString:#":"] objectAtIndex:0] intValue];
int enMin = [[[endTime componentsSeparatedByString:#":"] objectAtIndex:1] intValue];
int formStTime = (stHr*60)+stMin;
int formEnTime = (enHr*60)+enMin;
int nowTime = (currHr*60)+currtMin;
if(nowTime >= formStTime && nowTime <= formEnTime)
{
// Do Some Stuff..
}
The array timings contains you array. You may want to include the time in 24 hour format for uniformity.
NSDateFormatter *dateFormatter = [NSDateFormatter new];
[dateFormatter setDateFormat:#"HH:mm"];
NSDate *now = [NSDate date];
__block NSString *status = nil;
[timings enumerateObjectsUsingBlock:^(NSDictionary * dict, NSUInteger idx, BOOL *stop)
{
NSDate *date1 = [dateFormatter dateFromString:dict[#"time_from"]];
NSDate *date2 = [dateFormatter dateFromString:dict[#"time_to"]];
NSDateComponents *date1Components = [[NSCalendar currentCalendar]components:NSHourCalendarUnit|NSMinuteCalendarUnit
fromDate:date1];
NSDateComponents *date2Components = [[NSCalendar currentCalendar]components:NSHourCalendarUnit|NSMinuteCalendarUnit
fromDate:date2];
NSDateComponents *nowDateComponents = [[NSCalendar currentCalendar]components:NSHourCalendarUnit|NSMinuteCalendarUnit
fromDate:now];
NSInteger fromMinutes = date1Components.hour*60+date1Components.minute;
NSInteger toMinutes = date2Components.hour*60+date2Components.minute;
NSInteger nowMinutes = nowDateComponents.hour*60+nowDateComponents.minute;
if (nowMinutes>fromMinutes && nowMinutes<toMinutes) {
status = dict[#"timing_name"];
}
}];
NSLog(#"%#",status);

Xcode Iphone App: How to print price float [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Objective-C: How to format string as $ Price
I have an App showing prices.
The prices are displayed that way:
[self makePrice];
itemPrice.text = [NSString stringWithFormat:#"%i",tempPrice];
itemPrice.textColor = [UIColor whiteColor];
As a result big values are shown as: $ 12123041
I need it to be $ 12,123,041
How can I do it?
Thanks. Appreciate your help
Tim
hi you can do like this way:-
int tempPrice=123456;
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterCurrencyStyle];
NSNumber *yourNumber = [NSNumber numberWithInt:tempPrice];
NSString *str = [formatter stringFromNumber:yourNumber];
str = [NSString stringWithFormat:#"%#",str];
NSLog(#"my corrunsy === %#",str);
output is
hiiii === $123,456.00
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterCurrencyStyle];
NSNumber *num = [NSNumber numberWithInt:tempPrice];
NSString *str = [formatter stringFromNumber:num];
itemPrice.text = [NSString stringWithFormat:#"%#",str];

Limit a double to two decimal places without trailing zeros

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;
}