Doing Math with Objective C Double -


i've got loop in objective c , need coaching work out. i'm trying calculate height of 4 bars based on numbers stored strings in array, array. biggesttotal string containing largest of 4 objects in array. formatted each of elements in array currency.

for (int j=0; j<[array count]; j++) {         nslog(@"%@ %@ %@",[nsstring stringwithformat:@"%d", j], [array objectatindex:j], biggesttotal);     double barheight = (([[array objectatindex:j] doublevalue])*400.0/([biggesttotal doublevalue]));     nslog(@"%@",barheight);     cgrect currentrect = cgrectmake((150.0+(j*125.0)), (425.0-barheight), 100.0, barheight); // (x, y, width, height)     cgcontextaddrect(context, currentrect);     cgcontextdrawpath(context, kcgpathfillstroke); } 

with nslog statements above, console outputs follows:

0 $106,758.20 $106,758.20 (null) 1 $14,536.69 $106,758.20 (null) 2 $32,111.96 $106,758.20 (null) 3 $100,020.00 $106,758.20 (null) 

also, sadly no bars. missing here? why barheight (null)? appreciated...

barheight null* because @"$106,758.20" doesn't have valid doublevalue. rid of $ , ,** , should work.

also, if you're doing math currency, don't use double. use nsdecimalnumber


*actually 0.0 because can't converted, per docs, then, else has pointed out, you're trying log wrong format specifier: %@, objects, not double. since 0x0 nil, , 0x0 == 0.0 :), if try nslog(@"%@", 0.0);, "(null)" output. also, if do valid return doublevalue, attempt use %@ result in crash**, because you'll trying touch memory you're not supposed to.

**credit caleb (see comment) pointing out.


Comments