1

I'm trying to make a double Variance() function with the return value rounded to 4th decimal point. For example, if the result is 5.2992124 then it returns 5.2992, and returns 8.9914 if the result is 8.991382.

I know that there's cout << setprecision(~), printf("%.4d, ~"), but I'm not sure how to utilize that in my case.

Thanks in advance.

Jake Lee
  • 75
  • 8

2 Answers2

1

It depends what you need this for. It seems unusual to require a variance value rounded to some significant figures. In any case, you can round off your double as follows:

double rounded = 1e-4 * std::round(1e4 * value);

This multiplies by 10000 and rounds to a whole number, then divides by 10000.

paddy
  • 60,864
  • 6
  • 61
  • 103
1

A simple way would be to first convert the value into an integer. You can use c++'s pow() function defined in the header cmath:

pow(base, exponent)

In your example : 5.2992124.

(unsigned int) 5.2992124 * pow(10, 4).

This would yield the value 52992.124 which then becomes 52992 after truncation. You can then again convert it into a double by dividing it with pow(10, 4) and there you have it : 5.2992 as you wanted.