Skip to content

Instantly share code, notes, and snippets.

@bradphelan
Created September 17, 2013 07:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bradphelan/6591212 to your computer and use it in GitHub Desktop.
Save bradphelan/6591212 to your computer and use it in GitHub Desktop.
RoundToSignificantFigures
public static double RoundToSignificantDigits( double d, int digits )
{
var scale = (decimal) Math.Pow(10, Math.Floor(Math.Log10(Math.Abs(d))) + 1);
return (double)( scale * Math.Round((decimal)d / scale, digits));
}
[Fact]
public void RoundToSignificantDigits()
{
WMath.RoundToSignificantDigits(0.0012345m, 2).Should().Be(0.0012m);
WMath.RoundToSignificantDigits(0.0012645m, 2).Should().Be(0.0013m);
WMath.RoundToSignificantDigits(0.040000000000000008, 6).Should().Be(0.04);
WMath.RoundToSignificantDigits(0.040000010000000008, 6).Should().Be(0.04);
WMath.RoundToSignificantDigits(0.040000100000000008, 6).Should().Be(0.0400001);
WMath.RoundToSignificantDigits(0.040000110000000008, 6).Should().Be(0.0400001);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment