# Getting first digit of an integer(big or small)

I’m looking for a way to get the first digit of any integer. I’ve seen the digits function a lot on the net but it’s not working on my end. Could it be that there is a package I ought to add?
Also, how can I easily get the first digit of any integer and still maintain it as an integer?
I plan to use the integers for some calculations.

2 Likes

Assuming you want the most significant digit …

``````function firstdigit(x::Integer)
iszero(x) && return x
x = abs(x)
y = 10^floor(Int, log10(x))
z = div(x, y)
return z
end
``````
2 Likes

or if you don’t want to call the log10 function you can do:

``````z=abs(x)
while z >= 10
z = div(z,10)
end
return z
``````

This works, thanks a lot @JeffreySarnoff

I would now like to count the number of digits that are 1, 2, 3, …, 10 in an array of these firstdigits. How can I do that?

Surely there are library functions which will be faster, but one simple way is:

``````julia> function benford(ns)
xs = firstdigit.(ns)
[d => count(isequal(d), xs) for d in 0:9]
end;

julia> benford(trunc.(Int, abs.(1000 .* randn(1000))))
10-element Vector{Pair{Int64, Int64}}:
0 => 1
1 => 367
2 => 114
3 => 90
4 => 80
5 => 60
...
``````
2 Likes

Thank you @mcabbott. This works just fine.

`digits` works for me:

``````map(x -> last(digits(x)), (12, 13, 125, 36, 46, 57, 78))
(1, 1, 1, 3, 4, 5, 7)
``````

The most significant digits are at the end of the array.

1 Like

Yes, this is what I’m working on (or at least a generic version of it). Using that Benford’s function, it creates an array of pairs. But I only want to use the second part of the pair i.e the number of counts each digit appears. How can I do that?

Or a better way would be how to plot pairs against each other.

How can I plot the left pairs against the right?

You can try the bar plot from Plots.jl:

``````x = benford(trunc.(Int, abs.(1000 .* randn(1000))))
bar(first.(x),last.(x), xticks = (0:9, string.(0:9)))
``````

Just in case performance matters: the solution from @dlakelan is significantly faster, and, I suspect, close to theoretically optimal.

2 Likes

Thank you. It worked. Though my x = benford(firstdigits) because I want it to work for any number that comes into my first digits function. The first digits function takes input from a computation that works out the collatz conjencture for any number

Thank you. Now that I have the logic right, I’ll look into it for performance

Good point! I always look for performance first, correctness second 1 Like