I have the string representation of a percentage value, that goes to 6
places beyond the decimal point. Something like this:
64.123456%. I want to round that to 2 places and keep the percent sign at
the end e.g. 64.12% and return it as an NSString. I was playing around with
NSNumberFormatter (in code not IB) and was not able to either, keep the
percent sign or round properly, depending on the value passed to setStyle of
my NSNumberFormatter object. What I initially did was convert the string I
was passed into an NSNumber using NSString floatValue. This would loose the
percent sign at the end, but I could restore it by passing
setStyle:NSFormatterPercentStyle to the formatter. But when I did this, the
decimal was lost, so the number would end up like this:
64,1234%. I played around with my formatter using NSFormatterDecimalStyle or
NSFormatterPercentStyle, but never get what I wanted. Can these be used
together in the same formatter? or'd maybe? The docs don't say, it doesn't
work in any case, so I assume no. What I ended up doing was this:

// Takes a string containing a decimal percent
// rounds it off toNumPlaces and returns the
// resulting string
-(NSString*) roundValue:(NSString*)valueToRound toNumPlaces:(unsigned
int)places{

    NSLocale* locale = [NSLocale currentLocale];
    NSDecimalNumberHandler* roundingBehavior =    [NSDecimalNumberHandler
decimalNumberHandlerWithRoundingMode:NSRoundPlain scale:places
raiseOnExactness:NO

                 raiseOnOverflow:NO raiseOnUnderflow:NO
raiseOnDivideByZero:NO];
    NSDecimalNumber* fv = [[NSDecimalNumber
decimalNumberWithString:valueToRound ]
decimalNumberByRoundingAccordingToBehavior:roundingBehavior];

    NSNumberFormatter* formatter = [[NSNumberFormatter alloc] init];
    [formatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
    [formatter setNumberStyle:NSNumberFormatterDecimalStyle];
    [formatter setLocale:locale];

    NSString* newValue = [formatter stringFromNumber:fv ];
    [formatter release];

    return [NSString stringWithFormat:@"[EMAIL PROTECTED]@", newValue, @"%"];
}

Is this the best way to do this? It works just fine, but I was wondering if
there was a better way.
Thanks
-- 
"My break-dancing days are over, but there's always the funky chicken"
--The Full Monty
_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to [EMAIL PROTECTED]

Reply via email to