In a C++ code on linux x86_64, I need to double precision computing (+ or -).
26.100000000000001 – 26 + 0.10000000000000001
I got:
0.20000000000000143
I want to get 0.2.
here, the display format is not import, the computing results will be used for some if-else branch conditions. So, I only want the if-else conditions compare the 4 digits after the decimal digit.
It seems a rounding error ?
How to restrict the computing precision to 4 digits after decimal point ?
I do not want to call any functions in order to avoid overhead.
I do not want to use stringstream due to transformation overhead.
Any better ideas ?
thanks
The computing precision is fine. It’s the display precision you’re trying to control. You can do that with
setprecision()if using<iostream>or a formatter like"%.4f"if using<stdio.h>.You are already calling functions since you are displaying the result as decimal!
P.S.
0.1cannot be exactly represented by afloat,double, or any binary-mantissa format. It factors into(1/2) * (1/5), and decimal1/5is an infinitely-repeating digit sequence in binary.P.P.S. Go look at GMP. It might be your best hope.