tags:

views:

55

answers:

2

Hi,

I want to compare two double values till the second digit from decimal point. I am using following statement but I think it is not working properly.

dbl1.ToString("g2", CultureInfo.InvariantCulture).Equals( dbl2.ToString("g2", CultureInfo.InvariantCulture))

Am I missing anything here?

+1  A: 

You could use Math.Abs(dbl1 - dbl2) < 0.01. This will only consider the first two digits after the decimal point.

IVlad
Doesn't work, rounding screws that up. Example: 1.0049 vs 1.0099
Hans Passant
@Hans: what do you mean? `Math.Abs(1.0049 - 1.0099) < 0.01` returns true for me (in C# using .net 4.0).
IVlad
1.0049 prints as "1.00", 1.0099 prints as "1.01", not equal.
Hans Passant
@Hans: I'm sorry, but I don't see your point. As far as I understand the OPs question, he wants to compare two doubles up until the second digit after the decimal point, and as far as I can tell, this method works fine. What does printing have to do with it?
IVlad
A: 
dbl1.ToString("g2", CultureInfo.InvariantCulture).Equals( dbl2.ToString("g2", CultureInfo.InvariantCulture))

is working for me. I was just looking for any other alternative.

Ram