Setting the precision of a double without using stream (ios_base::precision)

后端 未结 3 1935
半阙折子戏
半阙折子戏 2020-12-19 09:40

Is there a way to do this without using the stream? For example, something like this:

double a = 6.352356663353535;
double b = a.precision(5);
3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-19 10:30

    A double always has the same internal precision (most probably 53 bits of binary precision), no matter what you do. It is only when writing out the double as text in decimal form where you can control the decimal precision of the output. So no, you cannot set the precision of a binary double precision number to anything else than it's native precision (let aside a decimal precision).

    If all you want is round a number to a given number of decimal digits, then consult Phillip's answer (but with the ammendments that john and Konrad made in their comments, of course). But note that this doesn't change the preicision of the underlying type and all computations with this number will be performed in binary double precision. Also such a rounded decimal number doesn't need to be represented exactly in the underlying binary floating point type.

    If you really want to perform exact decimal arithmetic, then you have to look for third-party libraries providing actual decimal floating point types.

提交回复
热议问题