RealDigits[523.502] gives me {{5, 2, 3, 5, 0, 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9}, 3}. Is there a way in run time to tell Mathematica not to offer high precision, ie, preserve whatever precision the input is given (returning {{5, 2, 3, 5, 0, 2}, 3} for the above)?
Please be mindful that the input can be any real number, I will not know the exact precision when I call this function.
Answer
This may seem counter-intuitive, but what works is to rationalize the number first,
Rationalize[523.502]
(* 261751/500 *)
This allows us to take advantage of the following property of RealDigits
For integers and rational numbers with terminating digit expansions,
RealDigits[x]returns an ordinary list of digits.
Combining the two then will give you what you are looking for,
RealDigits @ Rationalize @ 523.502
(* {{5, 2, 3, 5, 0, 2}, 3} *)
Comments
Post a Comment