Welcome to the MacNN Forums.

If this is your first visit, be sure to check out the FAQ by clicking the link above. You may have to register before you can post: click the register link above to proceed. To start viewing messages, select the forum that you want to visit from the selection below.

You are here: MacNN Forums > Software - Troubleshooting and Discussion > Developer Center > float rounding in cocoa

float rounding in cocoa
Thread Tools
Mac Enthusiast
Join Date: Oct 2001
Status: Offline
Reply With Quote
Oct 1, 2002, 12:03 AM
 
How does one round a float to say 2 decimal places? For instance:

1234.234535443238822
needs to be:
1234.23

at this point id be happy if i could just lop off everything after 2 decimals.
     
Forum Regular
Join Date: Oct 2001
Status: Offline
Reply With Quote
Oct 1, 2002, 08:39 AM
 
Originally posted by 3R1C:
How does one round a float to say 2 decimal places? For instance:

1234.234535443238822
needs to be:
1234.23

at this point id be happy if i could just lop off everything after 2 decimals.
is it for display only or will you need to use the rounded number for more calculations?

outputing a rounded float could be done with printf("%.2f", your_float); or with a NSNumber Formatter. to keep it a number you could try multiplying by 100, adding 0.5, grab the int value, and then divide by 100.

just an idea, there may be a much simpler way i am unaware of, ( a round(f, 2) function might exist or you might be able to use sprintf and the %.2f control string to get a string version of your float and then cast it to a float via a strtod call.

hope this helps,

kido
     
Mac Elite
Join Date: Sep 2000
Location: Tempe, AZ
Status: Offline
Reply With Quote
Oct 1, 2002, 02:29 PM
 
You can do
Code:
floor(x*100.0 + 0.5)/100.0
If you wanted a generalized routine that rounds to a specified number of decimals, you could do something like:
Code:
float MyRound(float x, unsigned int decimals) { float multiplyer = pow(10.0, (float)decimals); return floor(x*multiplyer + 0.5)/multiplyer; }
Geekspiff - generating spiffdiddlee software since before you began paying attention.
     
   
Thread Tools
Forum Links
Forum Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts
BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On
Top
Privacy Policy
All times are GMT -5. The time now is 01:52 PM.
All contents of these forums © 1995-2011 MacNN. All rights reserved.
Branding + Design: www.gesamtbild.com
vBulletin v.3.8.7 © 2000-2011, Jelsoft Enterprises Ltd., Content Relevant URLs by vBSEO 3.3.2