| View previous topic :: View next topic |
| Author |
Message |
TraxMate Master Cheater
Reputation: 0
Joined: 01 Mar 2008 Posts: 363
|
Posted: Tue Feb 03, 2009 10:01 am Post subject: [C++] swprintf() rounding |
|
|
| I'm using swprintf() to view a decimal number with only two decimals. It's working fine except from a minor problem, it's rounding up the number so instead of showing 63.63 (number is 63.6376) it's showing 63.64. I don't want it to be rounded at all, is there a way to make it not rounding the number with swprintf()?
|
|
| Back to top |
|
 |
Jani Grandmaster Cheater
Reputation: 2
Joined: 29 Dec 2006 Posts: 804
|
Posted: Tue Feb 03, 2009 11:11 am Post subject: |
|
|
| Code: | __inline double truncate(double d, int i)
{
int power = (int)pow(10,i);
return (double)((double)((int)(d*power))/power);
} | :P
|
|
| Back to top |
|
 |
TraxMate Master Cheater
Reputation: 0
Joined: 01 Mar 2008 Posts: 363
|
Posted: Tue Feb 03, 2009 11:58 am Post subject: |
|
|
| Jani wrote: | | Code: | __inline double truncate(double d, int i)
{
int power = (int)pow(10,i);
return (double)((double)((int)(d*power))/power);
} |
 | I don't quite understand how to use this. I know that pow is a declared in math.h and math isn't my strong side :p. I do know that I should put my number at 'd' but what should I put as 'i'?
|
|
| Back to top |
|
 |
Flyte Peanuts!!!!
Reputation: 6
Joined: 19 Apr 2006 Posts: 1887 Location: Canada
|
Posted: Tue Feb 03, 2009 2:18 pm Post subject: |
|
|
You enter the amount of digits after the decimal you want to keep.
Alternatively, you could do this:
| Code: | double inline truncate(double d, int i) throw()
{
int p = (int)pow(10.0,i);
return floor(d*p)/p;
} |
Pretty much the same thing, but doesn't abuse typecasting as a means to inhibit rounding.
|
|
| Back to top |
|
 |
TraxMate Master Cheater
Reputation: 0
Joined: 01 Mar 2008 Posts: 363
|
Posted: Tue Feb 03, 2009 2:56 pm Post subject: |
|
|
| Ok, now I understand. Thanks both of you for the help.
|
|
| Back to top |
|
 |
tombana Master Cheater
Reputation: 2
Joined: 14 Jun 2007 Posts: 456 Location: The Netherlands
|
Posted: Tue Feb 03, 2009 3:19 pm Post subject: |
|
|
| You could also subtract 0.005 from the number and then pass it to swprintf. That will result in always rounding down I think.
|
|
| Back to top |
|
 |
Jani Grandmaster Cheater
Reputation: 2
Joined: 29 Dec 2006 Posts: 804
|
Posted: Tue Feb 03, 2009 3:36 pm Post subject: |
|
|
| tombana wrote: | | You could also subtract 0.005 from the number and then pass it to swprintf. That will result in always rounding down I think. | That's a clever way too. I only thought about rounding with adding 0.005, but yeah, it will work the other way round too. But only with sprintf, not with the value itself.
|
|
| Back to top |
|
 |
|