Re: rounding a float
Re: rounding a float
- Subject: Re: rounding a float
- From: Kyle Moffett <email@hidden>
- Date: Sat, 29 Nov 2003 23:17:13 -0500
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
On Nov 29, 2003, at 19:17, Jay Rimalrick wrote:
What is the easiest way to round a float value with either c or
objective-c. I
need this float value to be consistent with the rounding of currency
e.g.
1.255 rounds to 1.26 and
1.254 rounds to 1.25
How about this:
float my_round(float number, int decimals) {
/* Generate the power of ten */
int i; float pow_ten = 1;
for (i = 0; i < abs(decimals); i++) pow_ten *= 10;
if (abs(decimals) != decimals) pow_ten = 1/pow_ten;
/* Actually do the rounding */
return( roundf( number*pow_ten +0.0 ) / pow_ten );
}
For rounding up change the "roundf" to "ceilf"
For rounding down change the "roundf" to "floorf"
For two digits in currency you could simplify this to:
#define ROUND_CURRENCY(number) \
( roundf( 100.0*(number) ) / 100.0 )
Cheers,
Kyle Moffett
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.3 (Darwin)
iD8DBQE/yW9Jag7LSGnFq10RAk4HAJ97uKSfzr9Ko02XihAJI79863KD3wCeNLyk
6kgL9b0HfKgCQwX5OqPpBSk=
=y3UC
-----END PGP SIGNATURE-----
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.