This code counts the number of digits in an integer.
let digitCount number = (int) (log10 ((float)number)) + 1;
For instance, it tells us 123456789 has 9 digits
.
let input = 123456789;
printfn "%i has %i digits" input (digitCount input);
https://dotnetfiddle.net/nxuoah
A weakness of the code is that it uses two casts. Can we use math to count the number of digits in an integer without having to cast twice? The reason to cast to a float is to make the type compatible with a the log10
function. The reason to cast back in to an integer
is to represent a "count" of digits instead of a "measure" of digits.
A second, related weakness of the code is the number of parentheses, which makes the code more difficult to read.
log10
seems like overkill. You can do this recursively by dividing (well, integer division) the number by 10 repeatedly. \$\endgroup\$