Rounding a double variable to be returned as opposed to printed
I am writing an average function that takes the average of an array and returns the answer in 2 decimal places. However, the only way I've found to do this on the internet is to use printf()
or cout()
.
But I don't want it to be printed every time this function is called because it is used in other functions such as the variance equation and standard deviation equation, which should not display the mean of the function.
If anyone could tell me a way to do this, I would be eternally grateful. I think my question is wide enough that the code is really unnecessary, but here it is just in case. It just goes on for a few decimal places. Not sure if this is the exact value or the cutoff point.
double avg(int a[],int n) // compute the average of n data storing in the array a
{
double addsum = (double)sum(a,n)/(double)n;
return addsum;
}
Since floating point values ββare always in binary, your best bet is to return the closest binary number to the decimal number you really want. But the process is relatively simple.
double round_two_places(double x)
{
return floor(x * 100.0 + 0.5) / 100.0;
}
Use the function ceil
from the header file math.h
as follows to round to two decimal places:
double avg(int a[], int n)
{
double addsum = (double) sum(a, n) / (double) n;
addsum = ceil(x * 100.0 - 0.5) / 100.0;
return addsum;
}
You can shift the value and remove it.
Sample code
double round(double value, unsigned n)
{
double shift = std::pow(10, n);
value *= shift;
value = (int) value;
value /= shift;
return value;
}
int main()
{
double value = 1.23456;
std::cout << "before: " << value << ", after: " << round(value, 2) << "\n";
return 0;
}
Caution . This code may not be sufficient for all use cases (for example, for round large numbers and / or rounding to many decimal places)
Output example
before: 1.23456, after: 1.23
std::round
gives you the closest integer to its argument. To simulate this rounding of the 3rd digit after the decimal point, use std::round(addsum*100.0)/100.0
.
double avg(int a[],int n) // compute the average of n data storing in the array a
{
double addsum = (double)sum(a,n)/(double)n;
return std::round(addsum*100.0)/100.0;
}