Skip to content

Instantly share code, notes, and snippets.

@henryw374
Last active September 23, 2023 10:59
Show Gist options
  • Save henryw374/0ff2fb0a0b08b3fbd96ad857d32cbd0e to your computer and use it in GitHub Desktop.
Save henryw374/0ff2fb0a0b08b3fbd96ad857d32cbd0e to your computer and use it in GitHub Desktop.
teaching my children how to get a computer to do their maths homework
(ns rounding-numbers
"teaching my child how to get a computer to do their maths homework"
)
(defn round-number [original round-to]
(let [small-bit (mod original round-to)
round-up? (>= small-bit (* 5 (/ round-to 10)))
medium-bit (mod original (* 10 round-to))
number-that-goes-up-or-stays-the-same (- medium-bit small-bit)
big-bit (- original medium-bit)]
(+ big-bit
(if round-up?
(+ number-that-goes-up-or-stays-the-same round-to)
number-that-goes-up-or-stays-the-same))))
; doesnt change
(round-number 100 10) ; => 100
; rounds up, keeping bigger-part
(round-number 115 10) ; => 120
; biggest number changes
(round-number 15 10) ;=> 20
(round-number 163 100) ; => 200
; up, getting more digits
(round-number 847 1000) ; => 1000
; round down
(round-number 847 100) ; => 800
(round-number 10 100) ; => 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment