Reputation: 319
In my project, I have a function that runs and spits out a 5 digit number into a label on my interface. The number can be a double or a float but I would like it to display like ###+##.##
Example Number 12345.67
Shown like 123+45.67
The output will always be a 5 digit number with decimals. I researched data formatting specifically number formatting but haven't come across anything specific for this case. This is where I change the number to a string and assign it to a label. Please help and thank you in advance for your time.
NSString *outputNumber = [NSString stringWithFormat:@"%f",numberHere];
_stationing.text = outputNumber;
Upvotes: 2
Views: 1117
Reputation: 1027
Hope this help
NSStirng *numberString = [NSString stringWithFormat:@"%.2f",numberHere];
NSString *firstPart = [numberString substringWithRange:NSMakeRange(0, 3)];
NSString *secondPart [numberString substringWithRange:NSMakeRange(3, 5)];
NSString *outputString = [NSString stringWithFormat:@"%@+%@", firstPart, secondPart];
If the number's format is not permanent, you should check the length first.
Upvotes: 0
Reputation: 318894
There are a couple of ways this could be done.
NSMutableString *outputNumber = [[NSString stringWithFormat:@"%.2f", numberHere] mutableCopy];
[outputNumber insertString:@"+" atIndex:outputNumber.length - 5];
_stationing.text = outputNumber;
Another:
int high = numberHere / 100;
float low = numberHere - (high * 100);
NSString *outputNumber = [NSString stringWithFormat:@"%d+%.2f", high, low];
These approaches won't work well if the number is less than 100.
Upvotes: 1