Skip to content

Instantly share code, notes, and snippets.

@Protiguous
Last active Sep 5, 2021
Embed
What would you like to do?
Sanitize decimal numbers to the Nth decimal place
public static class Program {
public static void Main() {
var random = new Random();
for (int i = 0; i < 100; i++) {
Decimal test = (Decimal)(random.NextDouble()) * 100000M;
//test.Dump();
test.Sanitize().Dump();
}
}
}
public static class Ext {
/// <summary>
/// Truncate, don't round. Just chop it off after <paramref name="decimalPlaces"/>.
/// </summary>
/// <param name="number"> </param>
/// <param name="decimalPlaces"></param>
[Pure]
public static Decimal Sanitize(this Decimal number, UInt16 decimalPlaces = 8) {
number *= (Decimal)Math.Pow(10, decimalPlaces);
number = Math.Truncate(number); //Don't round. Just Truncate.
number *= (Decimal)Math.Pow(10, -decimalPlaces);
return number;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment