mre
mre

Reputation: 137

How to find length of digits in a number in Netlogo?

Let's say I have the following code:

let digits 10101010101

How do I find the length of the digits (=11) using efficient Netlogo code? The build-in length function only works for strings and lists. I cant find a way to convert this number to a string: There does not seem to be a function like read-from-string but for the opposite use-case.

Upvotes: 1

Views: 70

Answers (1)

Matteo
Matteo

Reputation: 2926

You can use word to get from whatever input to a string:

to-report digits-count [number]
  if (not is-number? number) [
    error "The input passed to 'digits-count' was not a number!"
  ]

  report length (word number)
end


; Then, in the Command Center:
observer> show digits-count 123438
observer: 6

Note that, if it is possible to have numbers with characters that are not digits (e.g. a decimal separator, a minus sign etc) you need to also remove those characters using remove:

to-report digits-count [number]
  if (not is-number? number) [
    error "The input passed to 'digits-count' was not a number!"
  ]
  
  let string (word number)
  set string (remove "." string)
  
  report length string
end

; Then, in the Command Center:
observer> show digits-count 234.45
observer: 5

Upvotes: 3

Related Questions