summaryrefslogtreecommitdiff
path: root/lib
diff options
context:
space:
mode:
authorunwox <me@unwox.com>2024-11-05 13:51:12 +0600
committerunwox <me@unwox.com>2024-11-05 13:51:12 +0600
commitad9691cf051c205c992064ab9d6c46c2aba79dd6 (patch)
tree198e5ffb185e81f6b8b429acbce54651f839e44c /lib
parent788523388d9e1c4531364958b261d0b6b84b1f87 (diff)
improve price formatting
Diffstat (limited to 'lib')
-rw-r--r--lib/string.fnl26
1 files changed, 25 insertions, 1 deletions
diff --git a/lib/string.fnl b/lib/string.fnl
index 6538827..3e6134e 100644
--- a/lib/string.fnl
+++ b/lib/string.fnl
@@ -43,4 +43,28 @@
(.. (trim (must (luna.utf8.sub str 1 len))) (or ellipsis "...")))
""))
-{: letters : empty? : split : ends-with : trim : truncate}
+(fn insert [str substr pos]
+ (.. (str:sub 1 pos) substr (str:sub (+ 1 pos))))
+
+(fn format-price [price]
+ (var price-str (tostring price))
+ (local dot-position (price-str:find "%."))
+ (local price-len (if dot-position
+ (- (pick-values 1 dot-position) 1)
+ (# price-str)))
+ (var cursor (- price-len 3))
+ (while (< 0 cursor)
+ (set price-str (insert price-str " " cursor))
+ (set cursor (- cursor 3)))
+ price-str)
+
+(fn test-format-price []
+ (assert (= (format-price 5123450.50689140) "5 123 450.5068914"))
+ (assert (= (format-price 123450.50689140) "123 450.5068914"))
+ (assert (= (format-price 1450.50689140) "1 450.5068914"))
+ (assert (= (format-price 14350) "14 350"))
+ (assert (= (format-price 100) "100"))
+ (assert (= (format-price 0) "0"))
+ (assert (= (format-price 0.5) "0.5")))
+
+{: letters : empty? : split : ends-with : trim : truncate : format-price}