Solved

Rounding w/ float

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

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
C++ get user from AD  (VS6) 7 111
c++ reading data from file into two dimensional array 3 148
draw a Christmas tree by using a nested loop? 26 104
boost::uuid crashes 17 61
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…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.

732 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