round_half_to_even.sf 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. #!/usr/bin/ruby
  2. func round_nth(orig, nth) {
  3. var n = orig.abs
  4. var p = 10**nth;
  5. n *= p;
  6. n += 0.5;
  7. n -= 0.5 if n.is_odd;
  8. n = n.int;
  9. n /= p;
  10. n = -n if (orig < 0);
  11. return n;
  12. }
  13. var tests = [
  14. # original | rounded | places
  15. [+1.6, +2, 0],
  16. [+1.5, +2, 0],
  17. [+1.4, +1, 0],
  18. [+0.6, +1, 0],
  19. [+0.5, 0, 0],
  20. [+0.4, 0, 0],
  21. [-0.4, 0, 0],
  22. [-0.5, 0, 0],
  23. [-0.6, -1, 0],
  24. [-1.4, -1, 0],
  25. [-1.5, -2, 0],
  26. [-1.6, -2, 0],
  27. [3.016, 3.02, 2],
  28. [3.013, 3.01, 2],
  29. [3.015, 3.02, 2],
  30. [3.045, 3.04, 2],
  31. [3.04501, 3.05, 2],
  32. [-1234.555, -1000, -3],
  33. [-1234.555, -1200, -2],
  34. [-1234.555, -1230, -1],
  35. [-1234.555, -1235, 0],
  36. [-1234.555, -1234.6, 1],
  37. [-1234.555, -1234.56, 2],
  38. [-1234.555, -1234.555, 3],
  39. ];
  40. tests.each { |t|
  41. var (n, expected, places) = t...
  42. var rounded = round_nth(n, places);
  43. print "#{n} rounded to #{places} digits is ";
  44. if (rounded == expected) {
  45. say rounded;
  46. }
  47. else {
  48. die "#{expected}, but got #{rounded}! This is wrong!";
  49. }
  50. }