 # Convert atom to number and keep the whole number 0140

I’m using: SWI-Prolog version: 6.6.6
I have the following code:
read_line(Stream, Number) :-
read_line_to_codes(Stream, Line),
atom_codes(Atom, Line),
atom_number(Atom,Number).

I have to insert the number 0140 but keep it all because I need it as it is (0140) for my problem. However, converting it to number with atom_number ruins the number to 140 and my solution for the problem gives false result.

Just keep it an atom then?

I want to work with it as a number because I want to take the first n digits of the number so I make integer divisions like 3550 div 100 gives 35 so I want the 0140 to split it in 0, 01, 014, 0140. Can I make this with atom (I am very new to Prolog) ?

Use `sub_atom/5` with the second argument Before set to 0 and the third argument Len greater than 0:

``````?- X = '0140', sub_atom(X, 0, Len, _, Y), Len > 0.
X = '0140',
Len = 1,
Y = '0' ;
X = '0140',
Len = 2,
Y = '01' ;
X = '0140',
Len = 3,
Y = '014' ;
X = Y, Y = '0140',
Len = 4.
``````

You can use `atom_number/2` after you split off the prefixes if you need to convert those to numbers.

Boris thank you for your help! Do you know how can I reverse digits of an atom ??? For example, I have this atom ‘1234’ and I want to take this ‘4321’.

I guess one straight-forward way of “reversing” an atom is to use `atom_chars/2` and `reverse/2`:

``````reverse_atom(Atom, Reversed) :-
atom_chars(Atom, L),
reverse(L, R),
atom_chars(Reversed, R).
``````

… but I have to admit that I don’t know what problem you are really solving. There might be a better approach altogether.