ex. 12345 => 12300
ex. 1.2345 => 1.23
ex. 0.0001234 => 0.000123
// 取得有效位數 private static double RoundToSignificantDigits(double d, int digits) { if (d == 0.0) { return 0.0; } else { double leftSideNumbers = Math.Floor(Math.Log10(Math.Abs(d))) + 1; double scale = Math.Pow(10, leftSideNumbers); double result = scale * Math.Round(d / scale, digits, MidpointRounding.AwayFromZero); // Clean possible precision error. if ((int)leftSideNumbers >= digits) { return Math.Round(result, 0, MidpointRounding.AwayFromZero); } else { return Math.Round(result, digits - (int)leftSideNumbers, MidpointRounding.AwayFromZero); } } }
參考: https://stackoverflow.com/questions/374316/round-a-double-to-x-significant-figures
沒有留言:
張貼留言