# Setting precision? C++

1. Oct 2, 2006

### FrostScYthe

Hey.. I'm having trouble achieving this in C++...

I'm trying to do an opperation but keeping only 2 decimals, and floor rounding.

((3.52 * 4.32)/3.26) + 2.34

So I have 3.52 * 4.32 = 15.2064, but then I just round to 15.20

then 15.20/3.26 = 4.662576687116, but then I just round to 4.66

... and so on...

anyone know how to achive this in C++, I've thought of the floor command but how do I see the precision to only 2 decimals?

2. Oct 2, 2006

### chroot

Staff Emeritus
At each intermediate step, you'll need to:

1) Multiply your floating-point numbers by 100.0 (to preserve two decimal places).

2) Cast them to first to integers and then back to floating-point (which will truncate the rest of the decimal places). Alternatively, you can use the floor() function to truncate.

3) Divide the resulting floating-point number by 100.0.

- Warren

3. Oct 2, 2006

### 0rthodontist

Why would you ever want to do that anyway? You'll just lose precision. It makes more sense to calculate with all the digits you have and only round at the end.

4. Oct 7, 2006

### FrostScYthe

Alright... I have the rounding working now, Thanks so much =).

I'm printing the matrix giving a precision of 5 decimal places... I use

int j, k;
for (j = 0; j < n; j++) {
for (k = 0; k < n + 1; k++) {
printf (" %10.5f ", a[k][j]);
}
printf("\n");
}
printf("\n");

however I want to vary the " %10.5f " to any precision I input... anyone know how to do this... I know there's a way with iomanip.. but I want to use printf because it does it nicer.

5. Oct 7, 2006

### Hurkyl

Staff Emeritus
I would prefer to advise using the C++ i/o library. But, if you insist...

The first argument to printf doesn't have to be a string constant...

6. Apr 6, 2007

### dimensionless

For more decimal places you could also try putting this in your code

cout.precision(16);

You need not use 16, but that(16 digits) is about the limit of you precision, if you are using type double.

Last edited: Apr 6, 2007