# How to preserve real number's precision

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.

• Related: (71572) Jul 21, 2018 at 3:14

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} *)

• 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. Jul 21, 2018 at 3:13