Julia: splitting a number into different digits

I am interested in writing a function to convert a number to words in Julia. For example, f(1234)go back to "one thousand two hundred and thirty-four".

They detain me, figuring out how to extract each digit and put it back in the number. The following works, but it's pretty ugly. Thanks

x = 123456789
digits = split("$x","")
intx = zeros(length(digits))
for i=1:length(digits) intx[i]=int(digits[i]) end
intx
+4
source share
2 answers

What about the digits function in the database?

In  [23]: x = 123456789

Out [23]: 123456789

In  [24]: digits(x)

Out [24]: 9-element Array{Int64,1}:
 9
 8
 7
 6
 5
 4
 3
 2
 1
+9
source

How about this:

x = 123456789
digits = Int[]  # Empty array of Ints
while x != 0
    rem = x % 10  # Modulo division - get last digit
    push!(digits, rem)
    x = div(x,10)  # Integer division - drop last digit
end
println(digits)  # [9,8,7,6,5,4,3,2,1]

To do this in the style in which you did it (which you probably shouldn't do), you can do

x = 123456789
digits = [int(string(c)) for c in string(x)]
println(digits)  # {1,2,3,4,5,6,7,8,9}

c in string(x) , c::Char. int(c) Chapter ASCII, , .

+5

All Articles