Solved

Rounding w/ float

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

NAS Cloud Backup Strategies

This article explains backup scenarios when using network storage. We review the so-called “3-2-1 strategy” and summarize the methods you can use to send NAS data to the cloud

Question has a verified solution.

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

What is C++ STL?: STL stands for Standard Template Library and is a part of standard C++ libraries. It contains many useful data structures (containers) and algorithms, which can spare you a lot of the time. Today we will look at the STL Vector. …
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 additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.

770 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