fork(1) download
  1. using System;
  2. using System.Linq;
  3.  
  4. public class Test
  5. {
  6. public static void Main()
  7. {
  8. Console.WriteLine(RoundToSignificantFigures(20.051M, 4));
  9. Console.WriteLine(RoundToSignificantFigures(20.001M, 4));
  10. }
  11.  
  12. private static readonly decimal[] Pows = Enumerable.Range(-28, 57).Select(p => (decimal)Math.Pow(10, p)).ToArray();
  13.  
  14. /// <remarks>https://stackoverflow.com/a/18146056/3194005</remarks>
  15. public static decimal RoundToSignificantFigures(decimal value, int significantFigures)
  16. {
  17. if (value == 0)
  18. return 0;
  19.  
  20. int d = Log10Ceiling(Math.Abs(value));
  21. int power = significantFigures - d;
  22.  
  23. decimal magnitude = (decimal)Math.Pow(10, power);
  24.  
  25. var res = Math.Round(value * magnitude) / magnitude;
  26. var invMag = 1/magnitude;
  27. return res + invMag - invMag;
  28. }
  29.  
  30. private static int Log10Ceiling(decimal value)
  31. {
  32. int log10 = Array.BinarySearch(Pows, value);
  33.  
  34. return (log10 >= 0 ? log10 : ~log10) - 28;
  35. }
  36.  
  37.  
  38. }
Success #stdin #stdout 0.04s 16492KB
stdin
Standard input is empty
stdout
20.05
20.00