IntegerLength[n]
will return the number of digits in an integer.
I could not find a corresponding function that worked for reals, so I wrote my own function, digitsInnumber[n]
, which works for both integers and reals
Being new to Mathematica, I'd like to know if what I've done is good Mathematica style and if not, is there a better way to do this?
Thanks to the commentators for pointing out various things that I missed. After further thought, I think the following function fixes all the bugs and oversights, except that I couldn't get all fractions to work, so I explicitly eliminated fractions.
digitsInRealOrInteger[x_] := (
If[ IntegerQ[x], Return[StringLength[ToString[x]]]];
If [Element[x, Rationals] === True,Return[Print["input cannot be a fraction"]]];
If[Element[x, Reals] === True ,Return[StringLength[ToString[x, InputForm]]-1]];
Return[Print["input must be real or integer"]]
)
I'm surprised that this turned out to be more involved than I originally expected and that I had to resort to a more procedural approach.
digitsInNumber[1.2+3.4I]
returns 10. Is that the intended behavior? $\endgroup$digitsInNumber[3/2]
gives 4. $\endgroup$ToString[n, InputForm]
will address the precision issue, i.e.StringLength[ToString[0.123456789, InputForm]]-1
will return 10. $\endgroup$RealDigits
, but there are several cases that need to be handled.RealDigits[23.45] RealDigits[23456] RealDigits[22/7] RealDigits[3/2] RealDigits[0.123456789] RealDigits[0.000123456789]
{{2, 3, 4, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, 2} {{2, 3, 4, 5, 6}, 5} {{3, {1, 4, 2, 8, 5, 7}}, 1} {{1, 5}, 1} {{1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0}, 0} {{1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0}, -3} $\endgroup$