Solved

Rounding w/ float

Posted on 1997-03-03
1
246 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
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

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

Unlike C#, C++ doesn't have native support for sealing classes (so they cannot be sub-classed). At the cost of a virtual base class pointer it is possible to implement a pseudo sealing mechanism The trick is to virtually inherit from a base class…
  Included as part of the C++ Standard Template Library (STL) is a collection of generic containers. Each of these containers serves a different purpose and has different pros and cons. It is often difficult to decide which container to use and …
The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.

706 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

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now