Solved

Rounding w/ float

Posted on 1997-03-03
1
265 Views
Last Modified: 2010-04-10
Take a look at the following code:

#include <conio.h>
#include <iostream.h>

void main()
{
  float MyVariable, YourVariable, OurVariable;
  MyVariable = 3.456;
  YourVariable = 3.75;
  OurVariable = MyVariable + YourVariable;
  cout << "Here is the value of OurVariable :" << OurVariable << endl;
}
 
I was wondering how I can round numbers in two ways:

1)  How can I round both values before I total them?

2)  How can I round the value of there sum to a certain number of decimal places?  
0
Comment
Question by:Don Juan
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
1 Comment
 

Accepted Solution

by:
bc022297 earned 30 total points
ID: 1161886
this will truncate a float

int i;
float f = 3.456;
i = (int)f;

this will round a float:
int  i;
float f = 3.456;
i = (int)(f + 0.5);

changing:

OurVariable = MyVariable + YourVariable;

to:

OurVariable = (int)(MyVariable+0.5) + (int)(YourVariable+0.5);

should do it.

Rounding to a specific number of digits:

try
float f = ((int)(3.45678 * 100))/100);

the (int)(3.45678 * 100) evaluates to 345 and dividing by 100 gives 3.45.

For n decimal places multiply and divide by 10^n.  of Course the limits of precision for floats and doubles still have to be taken into consideration.
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

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

Errors will happen. It is a fact of life for the programmer. How and when errors are detected have a great impact on quality and cost of a product. It is better to detect errors at compile time, when possible and practical. Errors that make their wa…
This article will show you some of the more useful Standard Template Library (STL) algorithms through the use of working examples.  You will learn about how these algorithms fit into the STL architecture, how they work with STL containers, and why t…
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 viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.

627 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