Clarity conversion string to uint

59 views Asked by At

I want to concatenate a string with an uint. Found the best method is to have two strings and concatenate them.

How can any uint be converted to a string?

1

There are 1 answers

0
LNow On BEST ANSWER

You divide the number by 10. You convert the remainder of the division into text, and divide the result by 10 again. And then repeat whole process until result of division is equal 0.

Because Clarity do not support loops you need to have something that will perform division, conversion to text and concatenation 39 times. Why 39? Because uint type can have up to 39 digits. One of the cheapest way to do it is to fold over predefined buffer.

(define-read-only (uint-to-ascii (value uint))
  (if (<= value u9)
    (unwrap-panic (element-at "0123456789" value))
    (get r (fold uint-to-ascii-inner 
      0x000000000000000000000000000000000000000000000000000000000000000000000000000000
      {v: value, r: ""}
    ))
  )
)

(define-read-only (uint-to-ascii-inner (i (buff 1)) (d {v: uint, r: (string-ascii 39)}))
  (if (> (get v d) u0)
    {
      v: (/ (get v d) u10),
      r: (unwrap-panic (as-max-len? (concat (unwrap-panic (element-at "0123456789" (mod (get v d) u10))) (get r d)) u39))
    }
    d
  )
)