Tell me more ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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?

share|improve this question

3 Answers

up vote 9 down vote accepted

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

share|improve this answer
1  
Analogously: ToString[ToString[#, FortranForm] & /@ numbers]. – J. M. 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

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.

share|improve this answer

Just ask for it in InputForm:

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

Out[1]= 3.539537889086625*^24
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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