[Trilinos-Users] precision double in for Teuchos XMLObject ostream

Hoemmen, Mark mhoemme at sandia.gov
Sun Mar 4 21:51:35 MST 2012

On Sat 03 Mar 2012 at 16:12, George Pau <gpau at lbl.gov> wrote:
> I have a code that read in an XML file, save it as a ParameterList
> and then write it to a new XML file again.  What I notice is that
> the precision of parameter of type double drops in the new XML file.
> For example, even though I specified 7 decimal points in the
> original XML file, my new XML file shows the same value to only 5
> decimal points.  Is there any way that I can maintain the precision
> in my new XML file?

I took a brief look at the conversion code, and it seems like the
issue is with Teuchos::ToStringTraits.  This traits class implements
conversion to strings (via Teuchos::toString()) for different types T.
The default implementation of ToStringTraits creates an
std::ostringstream, writes the object of type T to the ostringstream,
and returns the std::string version of the ostringstream.  Teuchos
does not override ToStringTraits for floating-point types, so
toString() uses the default implementation in that case.

This would explain why setting the precision of floating-point data in
the output file, as you do, has no effect.  The XML output code first
converts the floating-point value to a string (via toString()), then
writes the string.  This bypasses the precision you set for the output

This is really a bug that we should fix, so thank you for pointing
this out!  If you need a workaround, you could simply specialize
Teuchos::ToStringTraits for T = double, using an excessive precision.
I like to use round(52 * log10(2)) + 1 = 17 for double-precision real
values (please feel free to correct me if I've gotten this wrong).

namespace Teuchos {
class ToStringTraits<double> {
  static std::string toString (const double& t) {
    std::ostringstream os;
    os.setf (std::ios::scientific);
    os.precision (17);
    os << t;
    return os.str();

There is, in fact, an algorithm, due to Guy Steele (yes, Java's Guy
Steele) et al., for idempotent printing of finite-length
floating-point values.  One of these days it would be nice for us to
take the time to implement that algorithm and test it carefully.  For
now, cranking up the precision works fine.


More information about the Trilinos-Users mailing list