Solved

Question! Converting String to a double or Integer where the value is rounded up or down?

Posted on 2006-07-24
3
215 Views
Last Modified: 2010-04-01
Hi guys,

My question is about how, when received a string& one can take that string and convert it to double,
alternatively I want the string to be converted into an integer rounded up or down ie value in from string is 1.560008 then the int = 2 etc.

Here's how I failed to convert the string& to double:

void getValue(string& theValue) {
      double d;
      char l [256];
      l = theValue;
      d = atof(theValue);
      cout << d << endl;
      cout << flush;
}

any inputs are welcomed

All the best
Idar
0
Comment
Question by:Idarhillgaar
  • 2
3 Comments
 
LVL 7

Accepted Solution

by:
nafis_devlpr earned 250 total points
ID: 17166576
you can do it this way

 d = atof(theValue.c_str());

or

sscanf(theValue.c_str(), "%lf", &d);

for the second question, do the above then do this

int i= (int)(d+0.5);

hope this helps

Nafis
0
 
LVL 7

Expert Comment

by:nafis_devlpr
ID: 17166592
>> int i= (int)(d+0.5);

this will actually round the values, for example :

if 1.5 it will be 2
if 1.4 it will be 1

you can also use the ceil or floor to round-up or round-down the values, for exmple

if  1.5
then ceil(1.5) will give 2.0
and floor(1.5) will give 1.0


Nafis
0
 

Author Comment

by:Idarhillgaar
ID: 17166719
Fabulous answers - Have a good summer!

Cheers
Idar
0

Featured Post

Live: Real-Time Solutions, Start Here

Receive instant 1:1 support from technology experts, using our real-time conversation and whiteboard interface. Your first 5 minutes are always free.

Question has a verified solution.

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

Suggested Solutions

Templates For Beginners Or How To Encourage The Compiler To Work For You Introduction This tutorial is targeted at the reader who is, perhaps, familiar with the basics of C++ but would prefer a little slower introduction to the more ad…
Container Orchestration platforms empower organizations to scale their apps at an exceptional rate. This is the reason numerous innovation-driven companies are moving apps to an appropriated datacenter wide platform that empowers them to scale at a …
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.

775 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