开发者

How do I determine the number of places following a decimal in a floating point value?

In C++ you can use std::numeric_limits<FloatingPointType>::digits10 to find out exactly how many places of precision you can get before the decimal place. How do I find out how many decimal places I can get following it, if I know the number will always be fixed-point between 0 and 1 inclusive?

Edit: The reason I ask is that I have an external RNG generating doubles and piping them through to a second program using standard input and output, so if the randomly generated开发者_如何学JAVA numbers aren't output correctly to standard output, the second program can't grab their full values through standard input because they get truncated by the output of the first program, then rounded to representable values by the second program. I'd like to pipe the values between programs fully intact. Thanks


std::numeric_limits<FloatingPointType>::digits10 is the total number of decimal digits the type can exactly represent. If you write a number as 1234.56 or 1.23456 ⋅ 103 or 123456 ⋅ 10-2 doesn't matter for the number of exact digits, so there is no distinction between before and after the decimal place.


The maximum number of significant digits you can have is given by std::numeric_limits<...>::digits. This is typically 24 and 53 for IEEE floats and doubles, respectively.


The C++ standard doesn't guarantee you anything. If you have to strictly control the number of places after the decimal point, you have to write your own code to do so (fixed-format output for instance). Ultimately it depends on the compiler you are using. You would get better luck by using C and printf's formatting controls if you need control over the number of decimal places.


If you will always need a certain number of digits you'd be well advised to look into boost. For example the format library, or the numeric conversion library. If you haven't already, you also should read the Goldberg article about floating point numbers


You can use setprecision(n);, where n is the number of digits after the decimal point. For example, if I want 15 decimals in my output:

cout<< setprecision(15);

Note: don't forget to include the header file to use this function:

#include<iomanip>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜