MathGroup Archive 2010

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: String-to-Number Conversion Precision

  • To: mathgroup at smc.vnet.net
  • Subject: [mg112381] Re: String-to-Number Conversion Precision
  • From: Ben <benp84 at gmail.com>
  • Date: Sat, 11 Sep 2010 05:46:23 -0400 (EDT)
  • References: <i6crfo$sa1$1@smc.vnet.net> <i6d0cn$1l5$1@smc.vnet.net>

On Sep 10, 4:13 am, Peter Breitfeld <ph... at t-online.de> wrote:
> Ben wrote:
> > I'm reading real numbers from a file and I'm trying to convert them
> > from string format (with arbitrary precision) to real values with the
> > same precision as given in the strings.
>
> > For example, when I convert "1.867524468", I want the result to be set
> > to precision 10.  Instead, I get the following.
>
> > In[1]:=    string = "1.867524468"
> > Out[1]:= "1.867524468"
>
> > In[2]:=    x = ToExpression[string]
> > Out[2]:= 1.86752
>
> > The last 4-digits get cut off.  This is fine for when I do math with
> > the number because the extra digits are still stored, but not when I
> > want to rewrite the number to a different file.  When I convert the
> > number back to a string for file output, the last 4-digits remain
> > lost.
>
> > In[3]:=    ToString[x]
> > Out[3]:= "1.86752"
>
> > Is there a function or formula I can use to automatically set the
> > precision of these numbers to their precision in the string?  Thanks.
>
> Mathematica treats numbers with less then $MachinePrecision digits
> always as having MachinePrecision. It _displays_ them with 6 digits
> after the decimal point, but knows all the digits. You can display them
> using NumberForm or better (in this case) using InputForm. So
>
> In[3]:= ToString[InputForm[x]]
>
> will give you all the original digits.
>
> To set the precision for longer numbers according to the length of the
> input string you may use something like this:
>
> string = "1.867524468121212771299123312";
> x = ToExpression[string]
> SetPrecision[x, StringLength[string] - 1]
> {Precision[x], Accuracy[x]}
> InputForm[x]
>
> --
> _________________________________________________________________
> Peter Breitfeld, Bad Saulgau, Germany --http://www.pBreitfeld.de

That'll work.  Thank you!


  • Prev by Date: Spreadsheet-like data manipulation
  • Next by Date: Re: drawing polygon diagonals
  • Previous by thread: Re: String-to-Number Conversion Precision
  • Next by thread: an issue of consistency