Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 How do you round doubles similar to how the printf function does it?
Index -> Programming, C -> C Help
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
chaoswings




PostPosted: Sat Oct 06, 2007 5:07 pm   Post subject: How do you round doubles similar to how the printf function does it?

How do you round doubles similar to how the printf function does it?

if I have the following program....

main ()
{
double num;
num=12.45672

printf("%7.2lf");

}

printf will round it and put it up on the display....how do I round it in that exact fashion and then use it in an equation...

i tried do do it by using....


double round(double num){
double a1,result;
a1=(double)(num*100)/100;
result=a1;

return result;

}

but it doesn't round it the same way for all numbers
Sponsor
Sponsor
Sponsor
sponsor
Euphoracle




PostPosted: Sun Oct 07, 2007 1:23 am   Post subject: RE:How do you round doubles similar to how the printf function does it?

double round(double num){

double result;
result=(double)(((int)(num*100))/100);

return result;

}

Casting it to an int will kill the decimals after it has been multiplied by 100, then dividing it will keep the old ones when casting back to double. If you want more decimal places, I recommend adding something along the lines of:

int places = 3;
int rounder = pow(10, places);

and then:

result = (double)(((int)(num*rounder)/rounder);
md




PostPosted: Sun Oct 07, 2007 9:45 am   Post subject: RE:How do you round doubles similar to how the printf function does it?

you need to cast remainder to a double when you do the division, otherwise you'll be dividing an int by an int which results in an int.
Display posts from previous:   
   Index -> Programming, C -> C Help
View previous topic Tell A FriendPrintable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 3 Posts ]
Jump to:   


Style:  
Search: