public

RoundToSignificantFigures

  • Download Gist
RoundToSignificantFigure.cs
C#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
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);
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.