Reputation: 697
I am using the following code snippet to format numbers in an iPad project using UIKit.h, but I can't figure out how to make negative numbers show as red. What I've tried, based on the documentation, isn't working. Would appreciate some suggestions on this.
NSNumberFormatter *decimalStyle = [[[NSNumberFormatter alloc] init] autorelease];
[decimalStyle setFormatterBehavior:NSNumberFormatterBehavior10_4];
[decimalStyle setNumberStyle:NSNumberFormatterDecimalStyle];
[decimalStyle setPositiveFormat:@"###,###,##0"];
[decimalStyle setNegativeFormat:@"(###,##0)"];
Upvotes: 1
Views: 1466
Reputation: 593
Not sure if this will work on iOS but on OS X I do it like this:
//create new instance of NSNumberFormatter
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
//create mutable dictionary for storing formatting attributes
NSMutableDictionary *negativeNumberColor = [NSMutableDictionary dictionary];
//set red colour
[negativeNumberColor setObject:[NSColor redColor] forKey:@"NSColor"];
//apply red colour to number formatter
[numberFormatter setTextAttributesForNegativeValues: negativeNumberColor];
//set formatter on NSTable column cell
[[tableColumn dataCell] setFormatter: numberFormatter];
Upvotes: 2
Reputation: 15376
At the moment you cannot do that directly, what you can do is something like this:
UILabel *numberLabel = ...; // The label that will display your number
numberLabel.text = [decimalStyle stringFromNumber:myNumber];
numberLable.textColor = (myNumber.floatValue < 0.0f) ? [UIColor redColor] : [UIColor blackColor];
Upvotes: 4
Reputation: 125007
The answer depends on how you're drawing the text, but the idea is to simply draw the text in whatever color you want. For example, if you're drawing the number in a UILabel, you can set the textColor
of the label to red or black, as appropriate. If you're drawing the text using Core Text, you can use NSAttributedString and add a color attribute to the text in question. If you're rendering the text in HTML, you'd of course want to set the appropriate attribute of the HTML tag enclosing that text.
Upvotes: 1