Search code examples
iphoneiosobjective-cios6nsdecimalnumber

Objective C : Get correct float values(justified)


I worked a lot in it and can't find a solution. Even the title can't explain clearly.

I have three values weight, quantity and total

I had done the following

float wq = [[weightarray objectAtIndex:selectedint]floatValue];
float q = [quantity floatValue];
float total = wq * q;

for ex, if

[weightarray objectAtIndex:selectedint] = @"3.14";
quantity = 4;

then the result is

wq = 3.140000  q= 4.000000 total = 12.560000

but I need

wq = 3.14 total = 12.56   

what to do? I searched a lot, someone suggests to use NSDecimal,

NSDecimalNumberHandler *roundingBehavior = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundPlain scale:2 raiseOnExactness:FALSE raiseOnOverflow:TRUE raiseOnUnderflow:TRUE raiseOnDivideByZero:TRUE];

but the scale is not 2 here, wq value may have 3 or four numbers after point.

If the total = 2.30000100 means I need total = 2.300001 how to solve this?


Solution

  • There may be a more direct way to achieve it (which I don't know) but here's a suggestion...

    1. Convert to string as you already do.
    2. Use [myString hasSuffix:@"0"] to see if it ends in zero.
    3. Use [myString substringToindex:[myString length]-1] to create a new string without the final zero.
    4. Repeat.

    I know it's not elegant, but unless someone has a better solution, this will at least do what you want.

    UPDATE: scratch that - I just discovered [myString stringByTrimmingCharactersInSet:set]. Surely this must be what you need...?