13 September 2013

An iostream insertion wrapper to provide full-precision floating point output for C++

In C++ one often wants output full precision floating point data. Iostreams make this a pain. Especially when you'd like the results to line up nicely in your terminal without requiring everything to be in scientific notation. Because reading "12" as 12 is easier than parsing 1.2e+01.

From my research code Suzerain, here's a header-only stream insertion wrapper up to the task. First, a simple use case with output:

using suzerain::fullprec;
cout << fullprec<>(1.23456789012345678e-5) << endl; // "   1.23456789012e-05"
cout << fullprec<>(1.23456789012345678e-4) << endl; // "   1.23456789012e-04"
cout << fullprec<>(1.23456789012345678e-3) << endl; // "   1.23456789012e-03"
cout << fullprec<>(1.23456789012345678e-2) << endl; // "   0.012345678901235"
cout << fullprec<>(1.23456789012345678e-1) << endl; // "   0.123456789012346"
cout << fullprec<>(1.23456789012345678e+0) << endl; // "   1.234567890123457"
cout << fullprec<>(1.23456789012345678e+1) << endl; // "  12.345678901234567"
cout << fullprec<>(1.23456789012345678e+2) << endl; // " 123.456789012345681"
cout << fullprec<>(1.23456789012345678e+3) << endl; // "   1.23456789012e+03"
cout << fullprec<>(1.23456789012345678e+4) << endl; // "   1.23456789012e+04"
cout << fullprec<>(1.23456789012345678e+5) << endl; // "   1.23456789012e+05"

Now the code. You'll need to swap real_t for double in your context as suzerain::real_t is defined elsewhere.

No comments:

Subscribe Subscribe to The Return of Agent Zlerich