Search code examples
iosobjective-ccocoa-touchfontsnsnumberformatter

Change font for decimal part of a number


my question is, how do I change the font size for the decimal part of a number, example:

Example

So far I can separate the components of the number but I can't manage to find a solution to change the font size of the decimal part, here is what I currently have:

-(NSString *)formaterDecimale:(CGFloat)valeurReel{
NSNumberFormatter *numberFormatter =[[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
[numberFormatter setDecimalSeparator:@","];
[numberFormatter setNegativePrefix:@""];
[numberFormatter setGroupingSeparator:@"."];
[numberFormatter setRoundingIncrement:[NSNumber numberWithDouble:0.01]];
[numberFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];

NSString *formattedString = [numberFormatter stringFromNumber:[NSNumber numberWithFloat:valeurReel]];
return formattedString;

}

Best Regards.


Solution

  • You should create attributed string

    NSRange range = [formattedString rangeOfString:@"."];
    range.length = formattedString.length - range.location;
    
    
    NSDictionary *normalAttributes = @{ NSFontAttributeName : [UIFont systemFontOfSize:15],
                                       NSForegroundColorAttributeName : [UIColor blackColor] };
    
    NSDictionary *smallAttributes = @{ NSFontAttributeName : [UIFont systemFontOfSize:8],
                                       NSForegroundColorAttributeName : [UIColor grayColor] };
    
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:formattedString attributes:normalAttributes];
    [attributedString setAttributes:smallAttributes range:range];
    

    and then assign it to attributedText property of UILabel for example.

    UILabel *your_label; // do not forget to create and initialize it
    your_label.attributedText = attributedString;
    

    Some other controls like UITextView also can show attributed strings.

    May be this CGRect for selected UITextRange adjustment for multiline text? answer could be also interesting for you.