Hello all,

When calculating sin(M_PI) the computer outputs ~-3e-7. Unfortunately, in my program the error grows (it is multiplied by a number on the order of 1e10) into around -208. My question: is there a way to round a float/double to only 3 digits after the decimal point (I do not care for super high accuracy on the sine function but it looks really bad if the final answer is not 0 when it obviously should be)?

Thank you very much in advance,

Ilya

short answer -- no, you can't round the internal representation of floats and doubles. That's because many numbers cannot be represented exactly, there are mathametical reasons for that, which is over my head :) but has something to do with powers of 2.

However, you can display them rounded using printf("%3.4f") will print only the first 4 decimals.

double rounded = (double)((int)((unrounded*1000)+.5)/1000);

that only rounds to the nearest whole number and discards all deimal places.

#include <iostream>
using namespace std;

#define PI 3.14159265358979323846
int main(int argc, char* argv[])
{

	double unrounded = PI;
	double rounded = (double)((int)((unrounded*1000)+.5)/1000);

	printf("%f\n%f\n", unrounded,rounded);
	return 0;
}

Does it? I don't have a compiler here.

double rounded = (double)(((int)((unrounded*1000)+.5))/1000);

Well, try fiddling with it. You can get it to work like that somehow.

BTW, your program's half C, half C++.

BTW, your program's half C, half C++.

Nope. its all c++. Afterall c++ includes all of the standard c functions, turning them into c++ functions with the same name. :eek:

I originally wrote the program using cout instead of printf(), but printf() is easier to code when you need specific number of decimals.

I had to split the lines to make it work

#include <stdio.h>

#define PI 3.14159265358979323846
int main(int argc, char* argv[])
{

	double unrounded = PI;
	double rounded = (int)((unrounded*1000)+.5);
	rounded /= 1000;

	printf("%.8f\n%.8f\n", unrounded,rounded);
	return 0;
}

Ah, yes, my mistake:

double rounded = (double)(((int)((unrounded*1000)+.5))/1000.0);
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.