I can’t believe I can’t work out how to do this but what can I say, I can’t work it out.
I’m just trying to write numbers in standard format (as apposed to scientific notation).
I have read countless examples of how to achieve this using “setprecision(…)” and “fixed” and things but the problem is that the precision of the numbers isn’t known at compile time and entering a conservative estimate with ‘setprecision(…)’ leaves heaps of superfluous zeros about the place.
Here’s an example of what I’m after:
let: tau = 6.2831
tau * 0.000001 -> 0.0000062831
tau * 0.001 -> 0.0062831
tau -> 6.2831
tau * 1000 -> 6283.1
tau * 1000000 -> 6283100
At the moment I get:
tau * 0.000001 -> 6.2831e-006
tau * 0.001 -> 0.0062831
tau -> 6.2831
tau * 1000 -> 6283.1
tau * 1000000 -> 6.2831e+006
The only thing I can thing to do is to somehow extract the exponent of the double then if the exponent is positive ‘fix’ the precision to zero, otherwise set the precision to ‘-1 * exp’; but this seems like an extremely convoluted way to ‘turn-off’ scientific notation.
Anyone know a better way?
While most decimal fractions can’t be represented exactly by a binary FP number, and representing exactly a binary FP number can result in lot of digits, there are algorithms to format a binary FP as the simplest decimal number which will be read back as the original FP assuming a given rouding mode on input (i.e. 6.283100128173828125 will be formatted as 6.2831, but the next representable FP number will be formatted with 6 or 7 digits).
Sadly, formatted IO in C++ (and in C) have no way to ask for those algorithms to be applied.
%gof printf and the default setting of IOStream is the nearest available, but they are coupled with an automatic choice between fixed and scientific notation, they need a maximal precision and the elimitation of ending0isn’t really the same (they act on the exact decimal representation, they don’t try to find the simplest one).Note that those algorithms aren’t really simple, they need multiprecision arithmetic.