# Converting a large floating-point number to a single-line string

When I feed a large (or small) enough floating-point number to ToString, it produces a two-line string, with the first line containing only the exponent of 10:

In := ToString[12345.^6]
Out :=           24
3.53954 10


This creates problems because it's very counterintuitive when written to a log file. For example ToString[{51.5^7, 2, 3, 12345.^6}] would be written out as

           11                  24\n{9.60839 10  , 2, 3, 3.53954 10  }


which is practically unrecognizable for what it is, especially when inserted in the middle of other output. I would like to see output like

{9.60839E+11, 2, 3, 3.53954E+24}


or, if not that, I'd be fine with something like

{9.60839*^11, 2, 3, 3.53954*^24}


What can I do to print out floating-point numbers in a format suitable for single-line output?

-

Admittedly hackish, but you could use

numbers = RandomReal[10^10, 3]

ToString[ToString[#, CForm] & /@ numbers]


or

ToString[ToString[#, FortranForm] & /@ numbers]


It gives

{3.672422352722051e9, 8.491123505444411e9, 1.7587409493599138e9}


Mathematica usually likes to wrap long lines. This won't happen here because by default ToString uses PageWidth -> Infinity

-
Analogously: ToString[ToString[#, FortranForm] & /@ numbers]. –  Ｊ. Ｍ. Jan 22 '12 at 11:33
@JM Edited it into the answer, it's always good to draw attention to more functions. –  Szabolcs Jan 22 '12 at 12:52

Just ask for it in InputForm:

In[1]:= ToString[12345.^6, InputForm]

Out[1]= 3.539537889086625*^24

-

There is already a built in function to handle this — it's called ScientificForm. You can get the output you desire as:

ScientificForm[12345.^6, NumberFormat -> (#1 <> "E" <> #3 &)] // ToString
Out[1]= 3.53954E24


StringForm only affects the display, so to export it correctly as a string to a log file, you'll have to wrap it in ToString like I've done. If you're only going to display it, you can drop that.

-

I came upon this question when trying to add a number in scientific notation to a string in the label of a plot, which requires that (or at least looks better if) the number is written with the exponents properly typeset (i.e. like $1.453\times 10^4$). This is not really what's in the question but it's not covered exaclty in any of the answers so far and this is probably the best place to document it.

This can be done by applying ToString's option to format as TraditionalForm after applying the ScientificForm command. Thus,

"number=" <> ToString[ScientificForm[14531.456456, 4], TraditionalForm]


will produce

with a String head which can be fed to labels or combined with other strings.

-