The answer proposed by Alzaymar is very interesting and useful. But note that this is NOT entirely useful when working with float or double.
In general, you can use a similar approach to purely "granulate" floating point values:
public double Granularize(double value, double granularity) { var precision = (Decimal.GetBits((decimal)value)[3] >> 16) & 0x000000FF; return Math.Round(Math.Round(value / granularity, 0) * granularity, precision); }
Obviously, you can get ceiling methods for float / double using the same basic premise.
I just wanted to point out that using granularity, such as 0.1d, will NOT give a properly granular result without rounding to the finest detail. Sometimes you will receive a false inaccuracy somewhere around the 13th decimal place.
source share