Setting Precision in C++: Floor Rounding to 2 Decimals

  • Context: C/C++ 
  • Thread starter Thread starter FrostScYthe
  • Start date Start date
  • Tags Tags
    C++ Precision
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
5 replies · 28K views
FrostScYthe
Messages
80
Reaction score
0
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?
 
Physics news on Phys.org
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
 
FrostScYthe said:
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?
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.
 
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.
 
For more decimal places you could also try putting this in your code

count.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: