1

I'm trying to code a calculator with XCode, but then I saw that Numbers with a comma are just cutted of after the comma.

I am getting the Numbers with this code out of the textfield.

-(IBAction)Additionbutton:(id)sender{

NSString *firstString = field1.text;
NSString *secondString = field2.text;
float num1;
float num2;
float output;
num1 = [firstString floatValue];
num2 = [secondString floatValue];
output = num1 + num2
Solutionfield.text = [ [NSString alloc] initWithFormat:@"%.2f",output] ;

Is it possible to set the calculation that way, that it is able to handle points AND commas or do I have to convert them and if so, how can I do this?

Thank you :)

Flockez
  • 11
  • 2

2 Answers2

3

Maybe you should use: NSNumberFormatter

How to convert an NSString into an NSNumber

Community
  • 1
  • 1
CarlJ
  • 9,461
  • 3
  • 33
  • 47
0

I have experienced the same thing this morning, following solution worked for me:

NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
NSNumber *aNumber = [NSNumber numberWithFloat:[[yourFloatAsString stringByReplacingOccurrencesOfString:@"," withString:@"" ] floatValue]];
[numberFormatter setNumberStyle:kCFNumberFormatterDecimalStyle];
NSString *formattedNumber;
formattedNumber = [numberFormatter stringFromNumber:aNumber];
NSLog(@"formattedNumber: %@", formattedNumber);

Obviously not the most efficient solution possible. It works, but if you have some time I strongly suggest you to have a look at NSNumberFormatter Class Reference

Yunus Nedim Mehel
  • 12,089
  • 4
  • 50
  • 56