Comparing decimals consistently with its scale
-
25-05-2021 - |
문제
I've got two decimal to compare. One comes form a db table mapped with NHibernate with precision=22
and scale = 8
, let see an example value as I can see it in the watch:
77.47234902
the one that I'm comparing with is:
77.472349025229
of course strict equality fails. I know I can check if the difference being under a certain epsilon, I'm just asking since precision and scale are first citizen in the decimal representation, if there is a smartest way to do such a comparison.
EDIT Just elaborating the @V4Vendetta reply I created this extension method:
public static class ScaleComparer
{
public static bool ScaleEquals(this decimal lhs, decimal rhs, int scale)
{
decimal mult = (decimal)Math.Pow(10, scale);
return decimal.Truncate(lhs * mult) / mult == decimal.Truncate(rhs*mult)/mult;
}
}
It works, but I really feel there'shoud be something smarter :)
해결책
Maybe you could try on these lines (not sure if smartest)
bool iscompared = decimal.Truncate(77.472349025229M * 100000000.0M) / 100000000.0M == 77.47234902M;
return true
제휴하지 않습니다 StackOverflow