How to prevent ostringstream (or the like) from outputting scientific notation WITHOUT precision settings

I can’t believe that I can’t understand how to do this, but what can I say, I can’t solve it. I'm just trying to write numbers in a standard format (as indicated in scientific notation).

I read countless examples of how to achieve this using "setprecision (...)" and "fixed" and that’s all, but the problem is that the accuracy of the numbers is not known at compile time and a conservative estimate is introduced with 'setprecision (...) 'leaves heaps of extra zeros relative to the place.

Here is an example of what I need:

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 do is somehow extract the double indicator, then if the positive indicator "fix" the accuracy to zero, otherwise set the accuracy to "-1 * exp"; but this seems like an extremely confusing way of "turning off" scientific notation. Does anyone know a better way?

+4
source share
1 answer

While most decimals cannot be represented exactly by the binary FP, and representing exactly the binary FP can lead to many digits, there are algorithms for formatting the binary FP as the simplest decimal to be counted back, since the original FP assuming this input taxiing mode (i.e. 6.283100128173828125 will be formatted as 6.2831, but the next displayed FP number will be formatted with 6 or 7 digits).

Unfortunately, formatted IO in C ++ (and in C) has no way to ask these algorithms to be applied. %g for printf, and the default value of IOStream is the most accessible, but they are associated with automatic choice between fixed and scientific notation, they need maximum precision, and the exception ending 0 is not really the same (they act on the exact decimal representation, they don’t trying to find the simplest).

Note that these algorithms are not very simple; they need multiple-point arithmetic.

+1
source

Source: https://habr.com/ru/post/1402216/


All Articles