views:

125

answers:

2

in objective-c or iphone development has anyone ever done dynamic number formatting - something along the lines of "use kCFNumberFormatterDecimalStyle until the number gets too big, then use kCFNumberFormatterScientificStyle instead?"

i want to display a number with some sort of hybrid between the two, but i'm having a little trouble with implementing it. thanks in advance.

A: 

I'd say create a method for that somewhere:

NSString *NSStringFromNumberInHybridStyle(NSNumber *aNumber)
{
    if ([aNumber intValue > 100]) {
        // format with kCGNumberFormatterDecimalStyle
    } else {
        // format with kCGNumberFormatterScientificStyle
    }
}
drvdijk
A: 

An other way would be selecting the formatter inline using the elvis operator:

// assuming you have formatter declared previously
// and x is the float NSNumber you want to format

formatter = ([x floatValue] < 1000.0) ?
               kCGNumberFormatterDecimalStyle :
               kCGNumberFormatterScientificStyle;

// Format with formatter

You would probaly want to put all of this in a #define or a method though.

szzsolt
thanks - one more question... what's the maximum 32-bit decimal value for CGFloat? it looks like the maximum value is 3.40282347e+38F but i'll be starting off at decimal and working up, so i'm trying to figure out the cutoff point. :) thanks again!
taber
CGFloat is either typedef'd as double or as float depending on your environment. The maximum value is CGFLOAT_MAX, which equals either DBL_MAX or FLT_MAX.
szzsolt
ah-ha. i guess what my real question is, since i'm defining my number as: CGFloat num; and using [formatter setNumberStyle:kCFNumberFormatterDecimalStyle]; out of the gate, what is the maximum "decimal" value num can be (i keep adding 1.0f each iteration) before i need to switch it over to use kCGNumberFormatterScientificStyle? thanks!
taber
nevermind, i ended up going through tons of hoops using NSDecimalNumber and kCFNumberFormatterDecimalStyle instead. thanks a bunch though!
taber
You're absolutely welcome
szzsolt