I want to compare 2 double but without all the digits. for example i have this double 1.548799778 and this 1.547990978 and I want to compare 1.xx from each. How can I "round" this double to 1.xx?? Thanks
One technique will be using the trunc
function like this:
double d1, d2;
d1 = 1.548799778;
d2 = 1.547990978;
if (trunc(d1*100) == trunc(d2*100)) {
// do your thing
}
Using 100
because you want two decimal places. You can use other numbers if you want more or less decimal places.
to compare that x
and y
are near enough, something like
(x==0.0 && y==0.0) || fabs(x-y)/max(fabs(x),fabs(y))<1e-6
to round x
use floor(x)
or ceil(x)
as suggested by Jan Vorcak
Addenda: I'm not sure that it will work for NaN (the details give headache)
Another possibility is to just use a comparison with tolerance.
if (fabs(a - b) <= tolerance) { .... }
choose your tolerance on how much precision you want.
For example, you can choose tolerance to be 0.001 to use about the first 2 digits.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With