Francis Smart
Francis Smart

Reputation: 4065

Julia: breaking number into different digits

I am interested in writing a function to convert a number to words in Julia. Such as f(1234) return to "one thousand two hundred and thirty-four".

I am getting held up on figuring out how to extract each digit and turn it back into a number. The following works, but it is pretty ugly. Thanks

x = 123456789
digits = split("$x","")
intx = zeros(length(digits))
for i=1:length(digits) intx[i]=int(digits[i]) end
intx

Upvotes: 6

Views: 2850

Answers (2)

quinnj
quinnj

Reputation: 1268

How about the digits function in Base?

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

Upvotes: 14

IainDunning
IainDunning

Reputation: 11664

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 it in the style you were doing 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}

Where c in string(x) iterates over the characters of the string, so c::Char. int(c) would give us the ASCII chracter code, so we need to change it back to a string then convert to integer.

Upvotes: 7

Related Questions