summaryrefslogtreecommitdiff
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
parent788523388d9e1c4531364958b261d0b6b84b1f87 (diff)
improve price formatting
-rw-r--r--bin/serve.fnl5
-rw-r--r--lib/string.fnl26
2 files changed, 28 insertions, 3 deletions
diff --git a/bin/serve.fnl b/bin/serve.fnl
index 884fb4f..06ecd22 100644
--- a/bin/serve.fnl
+++ b/bin/serve.fnl
@@ -299,14 +299,15 @@
[:a {:href link :style "text-decoration: none;" :rel "nofollow"}
[:NO-ESCAPE (.. "<h2>" (unescape product.title) "</h2>")]]
[:div {:class "price"}
- (if product.price (.. product.price "₽") "")
+ (if product.price (.. (str.format-price product.price) "₽") "")
(if (< 0 product.weight)
[:NO-ESCAPE (.. "за&nbsp;" product.weight "&nbsp;гр.")]
"")
(if (and (< 1 product.weight)
product.price-per
(< 0 product.price-per))
- [:NO-ESCAPE (.. " (" product.price-per "₽ за&nbsp;1&nbsp;гр.)")]
+ [:NO-ESCAPE (.. "<br> (" (str.format-price product.price-per)
+ "₽ за&nbsp;1&nbsp;гр.)")]
"")]])
(fn paginator-template [form page limit total]
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}