3

I want to show float digits in textfield upto two decimal points as entered in an ATM machine to withraw amount. like, 0.03. if i enter a new digit say 6, it would be like, 0.36 and so on. Please suggest me the way to do so. Thanks

Mohit Manhas
  • 3,471
  • 1
  • 17
  • 21

4 Answers4

2

hey check this like a ATM Functionality...

    NSString *str = @"1234987";
    NSUInteger len = str.length;
    if (len>0) {
        if (len==1) {
            str = [NSString stringWithFormat:@"0.0%@",str];
            NSLog(@"%@",str);
        }
        else if (len==2) {

            str = [NSString stringWithFormat:@"0.%@",str];
            NSLog(@"%@",str);
        }
        else {
            NSString  *pointstr = [str substringWithRange:NSMakeRange(len - 2,2)];
            NSString *Bstr = [str substringWithRange:NSMakeRange(0,len-2)];
            str = [NSString stringWithFormat:@"%@.%@",Bstr,pointstr];
            NSLog(@"\n\n FullString %@",str);
        }
    }
    else{
          str = @"0.0";
    }

OutPut is : FullString 12349.87

Enjoy with this code..

Paras Joshi
  • 20,427
  • 11
  • 57
  • 70
1
     NSNumberFormatter* decimalFormatter = [[NSNumberFormatter alloc] init];
        [decimalFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
        [decimalFormatter setMaximumFractionDigits:2];
        [decimalFormatter setMinimumFractionDigits:2];
NSString *enteredPrice=[decimalFormatter stringFromNumber:[NSNumber numberWithDouble:unitprice]];

You can use decimal formatter

Pandey_Laxman
  • 3,889
  • 2
  • 21
  • 39
  • Where do i use this, i mean which delegate method of UITextfield i can use. As i have to display the entered numbers in a textfield. – Mohit Manhas Nov 29 '12 at 08:35
  • - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string; – Pandey_Laxman Nov 29 '12 at 08:45
  • can you please make a code for me having the above method that can input characters in 0.00 format from rightmost position? – Mohit Manhas Nov 29 '12 at 09:24
0

Here you go:

float yourFloat = 2.45678;
NSString *text = [NSString stringWithFormat:@"%.2f", yourFloat];
textField.text = text;
pbibergal
  • 2,901
  • 1
  • 17
  • 19
0

I have open sourced SATextField which has this functionality built-in. You'll want to set fixedDecimalPoint to YES.

EDIT: I have created a new project that contains this functionality: STAControls (specifically, use STAATMTextField -- it even supports . entry!). The difference is that this project has been implemented as a legitimate subclass of UITextField whereas SATextField was merely a container class housing a UITextField instance.

Stunner
  • 12,025
  • 12
  • 86
  • 145