[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

rounding question

Posted on 2004-11-30
12
Medium Priority
?
538 Views
Last Modified: 2013-12-14
I'm currently using microsoft visual c++ .net version 7.1.3088

I need to round a double value.
I tried the following code

                  stringstream ssConvert("");
                  // initially I retrieve the value from my class where it's a string
                  string tempStr = m_ColumnData.at(i);
                  double dblValue = atof(tempStr.c_str());
                  // now I try use Math rounding function
                  dblValue = Math::Round(dblValue, 2); // I need to round to 2 decimal places
                  ssConvert.precision(2);
                  ssConvert << dblValue;
                  m_ColumnData[i] = ssConvert;

When I compile, I get error C2653: 'Math' : is not a class or namespace name

I tried to
#include <cmath> or math.h and I'm getting the same compiler error.

Thanks in advance
0
Comment
Question by:healingtao
  • 3
  • 3
  • 2
  • +2
12 Comments
 
LVL 14

Expert Comment

by:wayside
ID: 12709497
Math::Round is a .NET function, unless you are writing managed C++ code you can't use it.

For regular C++, one way would be to add 0.005 to the number before putting it to the stringstream.

 ssConvert << (dblValue + 0.005f);

0
 
LVL 14

Expert Comment

by:wayside
ID: 12709604
You could also round it arithmetically:

dblValue = (  (int)((dblValue + 0.005f) * 100.0f) )  /100.0f;

as long as your original number *100 doesn't exceed a 32 bit integer.

Because of the internal representation of floating numbers, though, you might wind with

x.499999999999999999  instead of  x.50000000000000, which puts you right back where you started from... you'll have to try it and see it if works for your range of values.

0
 
LVL 2

Expert Comment

by:pb_india
ID: 12709685
Have you tried adding the math.h header file to your code?  That might work, but not sure.  Math::Round(double, int) basically means that the first parameter (double) can be a number like 2.34785647 and the second parameter (int) tells how many decimal places to round off to. So Math::Round(2.34785647, 1) would return 2.3   Hope that this helps.  
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
LVL 20

Expert Comment

by:ikework
ID: 12709708
or this way:

void round( double &dblVal )
{
    double dblTemp = floor( dblVal * 100.0f );
   
    dblVal *= 100.0;

    if( dblVal - dblTemp >= 0.5 ) dblVal = dblTemp + 1.0;
    else dblVal = dblTemp;

    dblVal /= 100.0;
}

good luck ;)
ikework
0
 
LVL 2

Expert Comment

by:pb_india
ID: 12709743
This will handle all double's and you can spesify the number of digits.

double Round(double Value, int Precision)
{
     static const double Base = 10.0f;
     double Complete5, Complete5i;
     
     Complete5 = Value * pow(Base, (double) (Precision + 1));
     
     if(Value < 0.0f)
          Complete5 -= 5.0f;
     else
          Complete5 += 5.0f;
     
     Complete5 /= Base;
     modf(Complete5, &Complete5i);
     
     return Complete5i / pow(Base, (double) Precision);
}
0
 
LVL 20

Expert Comment

by:ikework
ID: 12709752
@pb_india: the standard-c-header math.h doesn't have any class Math, it's a c-header... no classes,
the c++-standard-header cmath doesn't have it as well,
i guess it's a microsoft-class as wayside said above....
0
 

Author Comment

by:healingtao
ID: 12713631
pb_india ,

I like  the code you provided but I have a slight problem with it.
Here is the sample I'm using to test this

#include "stdafx.h"
#include <math.h>
#include <sstream>
#include <fstream>
#include <string>

double roundVal(double Value, int Precision);
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
      double dblValue;
      stringstream ssConvert("");
      string tempStr = "12343.234233445";
      dblValue = atof(tempStr.c_str());
      dblValue = roundVal(dblValue, 6);
      ssConvert.precision(6);
      ssConvert << dblValue;
      string finalVal = ssConvert.str();

      return 0;
}

double roundVal(double Value, int Precision)
{
     static const double Base = 10.0f;
     double Complete5, Complete5i;
     
     Complete5 = Value * pow(Base, (double) (Precision + 1));
     
     if(Value < 0.0f)
          Complete5 -= 5.0f;
     else
          Complete5 += 5.0f;
     
     Complete5 /= Base;
     modf(Complete5, &Complete5i);
     
     return Complete5i / pow(Base, (double) Precision);
}

When I use precision 6 in this case my finalVal is 12343.2 but I need 12343.234233
When I increase precision say to 20 I thought that it'll fix the problem but I get "12343.234233445". I thought precision only counts decimals but apparently it's the whole number. I need something generic because I have a lot of big values with up to 9 decimal places.
Does it make sense  to take count the real number part (in this case 5) and add number of decimals(in this case 6) , add them and set precision(11) ???
Or is there an easier way?

Thanks
0
 
LVL 2

Expert Comment

by:pb_india
ID: 12717353
healingtao ,

Problem is in your code. The function I provided is fine.
Preision 1 would round it to 1 after decimal
Precision 2 will round it to 2 digits after decimal

See below: The commments on cout

double dblValue=0;
     stringstream ssConvert("");
        dblValue = 123.43234233445;//atof(tempStr.c_str());
  cout<<dblValue<<endl;  //   [RESULTis 123.432...this is before the function is used]
     dblValue = roundVal(dblValue,2);
   cout<<dblValue;//  [RESULT is 123.4 /...after the rounding is done to 1 ]
     ssConvert.precision(6);
     ssConvert << dblValue;
     string finalVal = ssConvert.str();
0
 
LVL 3

Expert Comment

by:esorf
ID: 12718740
Correction, pb_india.

Check out http://www.cplusplus.com/ref/iostream/ios_base/precision.html

Specifically:
  The precision determines the maximum number of digits that shall be output on insertion operations to express floating-point values, counting both the digits before and after the decimal point.
0
 
LVL 3

Expert Comment

by:esorf
ID: 12718777
So, Author, if you want to get X digits of precision following decimal:

outstream.precision((int)(log10(dblValue))+1+X)

Or in your case,

ssConvert.precision((int)(log10(dblValue))+7);  // For max 6 digits after decimal
0
 
LVL 14

Accepted Solution

by:
wayside earned 1000 total points
ID: 12720254
Sometimes the c runtime is the simplest...

char buf[50];
double dblVal = 1.234567;
sprintf(buf, "%.2f", dblVal); // sprintf takes care of rounding for you
dblVal = atof(buf);

if you want an arbitrary number of digits after the decimal point:

double round(double value, int precision) {
   char buf[50];
   sprintf(buf, "%.*f", precision, value); // sprintf rounds for you
  return atof(buf);
}
0
 

Author Comment

by:healingtao
ID: 12727423
wayside,

Thanks, exactly what I was looking for. Excellent, simple solution that is working great for all cases.
0

Featured Post

New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Article by: SunnyDark
This article's goal is to present you with an easy to use XML wrapper for C++ and also present some interesting techniques that you might use with MS C++. The reason I built this class is to ease the pain of using XML files with C++, since there is…
C++ Properties One feature missing from standard C++ that you will find in many other Object Oriented Programming languages is something called a Property (http://www.experts-exchange.com/Programming/Languages/CPP/A_3912-Object-Properties-in-C.ht…
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…
Suggested Courses

873 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question