Skip to content

Instantly share code, notes, and snippets.

@INeatFreak
Last active October 1, 2022 18:06
Show Gist options
  • Save INeatFreak/05fbf5c2a518d9177f9c54bd46f10445 to your computer and use it in GitHub Desktop.
Save INeatFreak/05fbf5c2a518d9177f9c54bd46f10445 to your computer and use it in GitHub Desktop.
Truncates the decimal places of given value to match desired decimal count.
/// <summary>Truncates the decimal places of <paramref name="value"/> to match <paramref name="decimalCount"/>.</summary>
/// <example> 1.14f.TruncateDecimals(1) --> 1.1f </example>
public static float TruncateDecimals(this float value, int decimalCount)
{
var rate = Math.Pow(10, decimalCount);
return (float) (Math.Truncate(value * rate) / rate);
// This below uses the rounding option, which is not precise:
//float rounded = (float)Math.Round(value, decimalCount, MidpointRounding.AwayFromZero);
//return rounded;
}
/// <summary>Truncates the decimal places of <paramref name="value"/> to match <paramref name="decimalCount"/>. </summary>
/// <example> 1.14d.TruncateDecimals(1) --> 1.1d </example>
public static double TruncateDecimals(this double value, int decimalCount)
{
var rate = Math.Pow(10, decimalCount);
return Math.Truncate(value * rate) / rate;
// This below uses the rounding option, which is not precise:
//double rounded = Math.Round(value, decimalCount, MidpointRounding.AwayFromZero);
//return rounded;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment