|
Hi,
two ways:
1.
use a rounding function; your math package sure has at least one.
2.
for numbers that fit easily in an integer, convert to integer and back; to get multiples of one tenth, do:
double roundToOneTenth(double number) {
return 0.1*(int)(10.*number);
}
Luc Pattyn [Forum Guidelines] [My Articles] Nil Volentibus Arduum
Please use <PRE> tags for code snippets, they preserve indentation, improve readability, and make me actually look at the code.
|
|
|
|
|
3. Use floor() : double d = floor(1.333333 * 10.) / 10.;
|
|
|
|
|
Thanks man, Your logic is really smart..
|
|
|
|
|
Hi,
The previous answers will not round correctly negative numbers and lack flexibility. Use the built-in facilities of the Standard C++ Library:
#include <sstream>
#include <iomanip>
double Round(double val, size_t decimal)
{
std::ostringstream oss;
oss << std::fixed << std::setprecision(decimal) << val << std::ends;
std::istringstream(oss.str()) >> val;
return val;
} cheers,
AR
When the wise (person) points at the moon the fool looks at the finger (Chinese proverb)
|
|
|
|
|
While this works, converting to a string, and then back to a float is a slow way of doing it. Check my other answer for alternatives that work.
|
|
|
|
|
Hi Andrew,
1 With a modern compiler implementing move semantics it is not that slow. You can also quicken it with a template for decimal.
2 It is safe, accurate and handles negative values.
3 It is flexible. You don't have to write a new one for each rounding you may need.
All in all this is an academic discussion Real world uses fixed point representations when needing rounded decimal values.
cheers,
AR
When the wise (person) points at the moon the fool looks at the finger (Chinese proverb)
|
|
|
|
|
Are you aware that floating points number have a rounding error ? You'll never be able to represent perfectly a float in memory. For more information google for "floating point precision".
|
|
|
|
|
My answer gets the nearest representation of the rounded value and produces corrrect string output.
cheers,
AR
When the wise (person) points at the moon the fool looks at the finger (Chinese proverb)
|
|
|
|
|
Yes sure, you can always print a floating point with the precision you want, but it doesn't mean that the float stored in memory is rounded properly. I simply wanted to make sure that he is aware of that.
|
|
|
|
|
Some of the suggested answers are ok, but are lacking correct rounding.
Luc Pattyn wrote:
double roundToOneTenth(double number) {
return 0.1*(int)(10.*number);
}
Should be:
double RoundToOneTenth(double nNumber) {
return (int)(10.0 * nNumber + 0.5) * 0.1;
}
While this solution works, it requires converting a floating point number to an integer and back to a floating point number. This is somewhat slow.
Hans Dietrich wrote:
double d = floor(1.333333 * 10.) / 10.;
Should be:
double RoundToOneTenth(double nNumber) {
return floor(nNumber * 10.0 + 0.5) * 0.1;
}
This is the solution I would recommend. Note that I changed /10 to *0.1 .
It is faster to multiply than to divide. In a simple case like this the compiler would make this change for you but I am just pointing this out.
Alain Rist wrote:
#include <sstream>
#include <iomanip>
double Round(double val, size_t decimal)
{
std::ostringstream oss;
oss << std::fixed << std::setprecision(decimal) << val << std::ends;
std::istringstream(oss.str()) >> val;
return val;
}
While this works and saves you from worrying about rounding errors, this is incredibly slow and uses much more memory (although still not much) than other solutions. There is no need for using strings for such a simple operation.
Having said that, it is good that people are posting alternatives to show just how many ways there are for doing this.
Cedric Moonen wrote: Are you aware that floating points number have a rounding error ? You'll never be able to represent perfectly a float in memory.
While this is absolutely true, it only affects really big numbers or numbers with a high precision.
For instance, 1.0 / 3.0 == 0.333333333333333314829616256247390992939472198486328125 (Wikipedia[^]).
If you are concerned about this, there are macros FLT_EPSILON (for float ) and DLB_EPSILON (for double ) which define the minimum perfect precision of a single operation.
|
|
|
|
|
..and in addition, there might be other interesting aspects of rounding. This[^] post on cplusplus.com brings a few of these up.
|
|
|
|
|
Andrew Brock wrote:
double RoundToOneTenth(double nNumber)
{
return floor(nNumber * 10.0 + 0.5) * 0.1;
} This is the solution I would recommend. Note that I changed /10 to *0.1.
-5.51 => -5.4
cheers,
AR
When the wise (person) points at the moon the fool looks at the finger (Chinese proverb)
|
|
|
|
|
Alain Rist wrote: -5.51 => -5.4
Not so bad, since we're talking round numbers.
|
|
|
|
|
That rounding calculation fails with negative numbers. This will work with positives, negatives, and zero :
int RoundValue( double value )
{
int result = 0;
if( value < 0 )
result = (int)( value - 0.5 );
else
result = (int)( value + 0.5 );
return result;
}
Also - yes, it is faster to mulitply than to divide but the percentage of difference is very small (around 10% in my tests) so that is not enough that I would worry about it. Actually, since it is so close I would refrain from changing to multiplies because occasionally it can result in a loss of clarity and the compiler will do it for us when it can.
modified on Wednesday, February 23, 2011 2:02 PM
|
|
|
|
|
Oops, I thought about this for the floor(), but it wasn't the case. Forgot about the casting one.
And yes, the percentage is small, but as a game developer any clock cycles I can save by simple things like this are worth it. I guess my views of what is important may differ from others, I prefer high performance over clarity.
|
|
|
|
|
I can understand that - to a point. If you are that concerned with performance there are a lot of other techniques you can use to get big gains in performance. One simple example : if a complex expression or calculation is repeated then save the result in a temporary variable. I have lost count of how many times I have seen people repeat expressions in code. Not only will this have higher performance it will also help maintenance and that is one of my highest priorities. It is been frequently stated that software usually spends more time undergoing maintenance than it does being developed and in my experience this is very true so I believe in making software as maintainable as possible and clarity is very important for this.
One more thing - as you said before, the compiler will convert to multiplies automatically when it can so, to me, it makes no sense to sacrifice clarity for something that is done for you transparently. In fact, I find it completely ridiculous but opinions vary.
|
|
|
|
|
You're putting too much value on your solution if you ask me.
|
|
|
|
|
thanks for the tip. I hadn't noticed that.
|
|
|
|
|
See also my answer to your previous question.
I must get a clever new signature for 2011.
|
|
|
|
|
I require some result based on the a float value to multiply with an int value.
like 146 * (1/1.3333333) result should be 109.50 but through program it's come out with 108.95. I have also tried float( 146 * (1/1.333333)) and float(146) * float(1/1.333333) but the result is same. I am getting surprised from this result. Can anyone help me out.
|
|
|
|
|
hi
for me its giving right answer. i did like this.
char ms[100];
int tk = 146;
int tl = 1;
float tm = 1.333333;
float tr = ((float)tk)*(tl/tm);
sprintf(ms, "%f", tr);
AfxMessageBox(ms);
how you are doing?
Regards,
A. Gopinath.
|
|
|
|
|
Do not use floats or doubles if you want to get accuracy in the decimal portion of your values. Floating point values in computers are held in such a way that accuracy cannot be guaranteed. There are many articles on the internet that explain why this is so.
I must get a clever new signature for 2011.
|
|
|
|
|
Hi everyone. I would like to know if it is possible to use Windows Forms from the System::Windows::Forms namespace in unmanaged C++. If it is possible, how is it done? Thanks.
|
|
|
|
|
It is not. If you wanna create gui apps with c++, dig around win32 APIs. CreateWindow is your friend.
011011010110000101100011011010000110100101101110
0110010101110011
|
|
|
|
|
I really need the datagridview tool in .net, any way of using it in Win32 API programming?
|
|
|
|