I'm making a program on my TI-84, and I'm in need of a way to count the digits of a number.
How would I go about doing that?
I'm making a program on my TI-84, and I'm in need of a way to count the digits of a number.
How would I go about doing that?
It's been a long time since I've touched TI-Basic, however, I do know that there is a mathematical means of counting digits of a number. Since each place is a multiple of 10, you should just be able to use the (base 10 log of your number) plus one. This is assuming you're using positive integers.
An alternative and more general solution is to get the length of the number converted to a string. Looks like there is some documentation here: http://tibasicdev.wikidot.com/number-to-string2
Seeing as you're using a TI-84, these 68k/NSpire answers won't specifically answer your question. It's easy enough to use 1+int(log(X)) for natural numbers, but what if you want to support non-zero integers as well? This program (only 9 bytes) should do the trick:
Prompt X
1+int(log(abs(X
If you want to count the negative symbol as a digit, just add (X<0)+
to the beginning of the second line.
I also have a whole different solution... for any real numbers, 15 characters of precision (including decimal point) and having the negative symbol count as a digit you can use the Number to String utility like so (10 bytes):
Prompt X:X
prgmS
length(Ans
Assuming it is a positive integer, you could subtract increasing powers of 10 from the number. If the result is less than 0 then the last power subtracted is the number of digits.
As an example, consider the number 643. First subtract 10 - gives 633 which is positive. Next try 100 - gives 543 which is positive. Next try 1000 - gives -357. Therefore the number of digits is 3 (given by 10^3).
Either
f(x)
:Func
: If x = 0
: Return 1
0 → n
: While x >= 1
x / 10 → x (integer division would be ideal)
n + 1 → n
: End
: Return n
:End Func
Or better
f(x) =
if x == 0 then return 1
return int(10log(x)) + 1
The 10log gives:
1-9 0.~
10-99 1.~
100-999 2.~
Also 10log x = log x / log 10.