1
$\begingroup$

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.

$\endgroup$
1
3
$\begingroup$

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} *)
$\endgroup$
1
  • $\begingroup$ This does not appear to be robust, e.g. RealDigits @ Rationalize[12.345678] gives {{1, 2, 3, 4, 5, 6, 7, 8, 0, 0, 0, 0, 0, 0, 0, 0}, 2} in v10.1 under Windows x64. $\endgroup$
    – Mr.Wizard
    Jul 21 '18 at 3:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.