Last active
August 3, 2020 13:53
-
-
Save punit-naik/4843727fed04327911cf34b647eaf1e7 to your computer and use it in GitHub Desktop.
Takes upto `n` non-zero integers after the decimal for a floating point number. This will skip zeros if present just after the decimal
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| (def round-n | |
| "Takes upto `n` non-zero integers after the decimal for a floating point number | |
| This will skip zeros if present just after the decimal" | |
| (memoize | |
| (fn [num n] | |
| (let [num (double num) | |
| [before-decimal after-decimal] (str/split (str num) #"\.") | |
| n (if (> n (count after-decimal)) (count after-decimal) n) | |
| str-not-zero? (fn [s] (not (zero? (Integer/parseInt s))))] | |
| (Double/parseDouble | |
| (str before-decimal "." | |
| (loop [ad after-decimal | |
| n-count 0 | |
| found-first-non-zero-num? (str-not-zero? (str (first ad))) | |
| result []] | |
| (if (or (= n-count n) | |
| (empty? ad)) | |
| (str/join "" result) | |
| (let [ad-first (str (first ad)) | |
| ad-rest (rest ad) | |
| found-non-zero? (str-not-zero? (str (nth ad-rest 0 0)))] | |
| (recur ad-rest | |
| (cond-> n-count | |
| found-first-non-zero-num? inc) | |
| (if (not found-first-non-zero-num?) | |
| found-non-zero? found-first-non-zero-num?) | |
| (conj result ad-first))))))))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment