3
$\begingroup$

I am trying to get from a number such as $12.345$ to a list $\{1,2,3,4,5\}$. My best attempt so far has been:

First[RealDigits[12.345]]

however this of course gives $\{1, 2, 3, 4, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0\}$ since it assumes the number to have infinite precision.

Any help is greatly appreciated

$\endgroup$
3
  • 1
    $\begingroup$ First[RealDigits[Rationalize[12.345]]]? $\endgroup$
    – J. M.'s torpor
    May 21 '17 at 18:44
  • 2
    $\begingroup$ What output do you expect for 100.00 ? $\endgroup$
    – Shadowray
    May 21 '17 at 19:00
  • $\begingroup$ Related: (110596) $\endgroup$
    – Mr.Wizard
    Jul 21 '18 at 3:13
3
$\begingroup$

12.345 does not have infinite precision, rather it has machine precision. If you specify the precision correctly your formulation will work as written:

First @ RealDigits[12.345`5]
{1, 2, 3, 4, 5}

I believe a modified input form like this is necessary to remove ambiguity; see:

J. M. proposed Rationalize in a comment but this cannot be relied upon, e.g.:

First @ RealDigits @ Rationalize[12.345678]
{1, 2, 3, 4, 5, 6, 7, 8, 0, 0, 0, 0, 0, 0, 0, 0}

Perhaps dropping any trailing zeros would be appropriate for your task:

First @ RealDigits[12.345678] /. {a___, 0 ...} :> {a}
{1, 2, 3, 4, 5, 6, 7, 8}
$\endgroup$
3
  • $\begingroup$ It works for his case, but not in general (which is why it was only a comment). $\endgroup$
    – J. M.'s torpor
    May 21 '17 at 19:10
  • $\begingroup$ Hi Mr.W. Could not respond to your comment re my deleted answer. I deleted it because it cannot handle 100.00 (which, I presumed, should be transformed to {1, 0, 0, 0, 0}). $\endgroup$
    – kglr
    May 21 '17 at 19:11
  • $\begingroup$ @kglr I see. But I think that is a problem with the OP's input format, i.e. it is an unreasonable expectation. We could perhaps drop only zeros to the right of the decimal point, but there is no way to differentiate 100.00 from 100.00000 etc.; the precision must be included in the input I believe. $\endgroup$
    – Mr.Wizard
    May 21 '17 at 19:14

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.