# math operation

Discussion in 'Mac Programming' started by gonche1124, Oct 1, 2009.

1. ### gonche1124 macrumors newbie

Joined:
Aug 6, 2009
#1
Hello,

I have two strings and I want to divide the length of each word and round up the result.
Can anyone help with this?

I've tried it with NSDecimalNumber but I get a bucnh of errors.

Thank you

Andres

2. ### kainjow Moderator emeritus

Joined:
Jun 15, 2000
#2
[str length] returns an int representing the number of characters. You can then divide it like any other number in C. The random() function can be used to round up a double.

If you still need help, post what code you're working with.

3. ### lee1210 macrumors 68040

Joined:
Jan 10, 2005
Location:
Dallas, TX
#3
I'm guessing you meant round(double), not random()... You'd probably get a very different result than you're hoping calling random.

-Lee

4. ### chown33 macrumors 604

Joined:
Aug 9, 2009
Location:
Sailing beyond the sunset
#4
I've been rounding with random() for years. It keeps the testers on their toes. No comment about all those avionics and nuclear-plant control systems I helped write.

5. ### kainjow Moderator emeritus

Joined:
Jun 15, 2000
#5
hehe oops, that is what I meant. Not sure why I put random

6. ### lloyddean macrumors 6502a

Joined:
May 10, 2009
Location:
Des Moines, WA
#6
It's unclear what you're asking for but the closest seems to be rounding of real numbers to integers, so ...

Code:
```	#include <math.h>

double	n;
float	f;
double	d;

n = 3.4;
f = floorf(n);	// results = 3
d = floor(n);	// results = 3
f = ceilf(n);	// results = 4
d = ceil(n);	// results = 4
f = roundf(n);	// results = 3
d = round(n);	// results = 3

n = 3.6;
f = floorf(n);	// results = 3
d = floor(n);	// results = 3
f = ceilf(n);	// results = 4
d = ceil(n);	// results = 4
f = roundf(n);	// results = 4
d = round(n);	// results = 4
```

Joined:
Aug 6, 2009
#7

8. ### jared_kipe macrumors 68030

Joined:
Dec 8, 2003
Location:
Seattle
#8
Just remember that you'll need to typecast the int that is returned by
-(NSUInteger) length;

such as

unsigned int test1, test2;
test1 = [@"test1 string" length]; // 12
test2 = [@"test2 string 1234" length]; // 17

double result;
result = (double)test1/test2; // ~0.7

NSLog(@"result = %0.2d", result); // prints "result = 0.71"
result = round(result);
NSLog(@"result = %0.2d", result); // prints "result = 1.00"

Just remember one thing, the round function rounds UP .6 and rounds DOWN .5 Unlike how you learned in elementary school.