简体   繁体   中英

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?

I'm not entirely sure what it is your asking for, but it seems as if you want the values to only display a 2 dp In which case you could use a string format like so:

    NSString *output = [NSString stringWithFormat:@"float = %.2f", 3.14];

The .2 specifies that the float should be justified to 2 dp

Hope this helps

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...?

Finally solution found, thanks to Martin

float total = 12.56000;
NSString *s = [NSString stringWithFormat:@"%f", total];
NSLog(@"%@",s);
BOOL success;
success =NO;
while(!success)
{
    if ([s hasSuffix:@"0"])
    {
       s = [s substringWithRange:NSMakeRange(0,[s length]-1)];
    }
    else if ([s hasSuffix:@"."])
    {
        s = [s substringWithRange:NSMakeRange(0,[s length]-1)];
        success = YES;
    }
    else
        success = YES;
}
NSLog(@"%@",s);

if total = 12.560000 it returns total = 12.56

if total = 12.000000 it returns total = 12

if total = 10.000000 it returns total = 10

if total = 12.3000100 it returns total = 12.30001

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM