Krishna Bharadwaj
Krishna Bharadwaj

Reputation: 625

Issues with C++ Precision

I saw a number of posts which spoke about how we can display a number with a given precision in C++, but I was wondering if there is a way to display non recurring numbers as say x.0 and recurring numbers of width specified by the setprecision method?

Upvotes: 2

Views: 181

Answers (2)

Potatoswatter
Potatoswatter

Reputation: 137910

It sounds like what you really want is to trim trailing zeroes. The machine doesn't know whether a number is really a "recurring number," which is just a fancy name for a rational number whose denominator is relatively prime from the numeric base, because floating point math is not based on rational numbers.

As Adam mentioned, the default output style is already to omit trailing zeroes. This hasn't much to do with math; it's just deleting the characters from the end of the string.

In terms of the Standard, the ios_base::fixed and ios_base::scientific flags determine qualitative formatting. If neither is set, the output is equivalent to the %g format specifier of printf.

According to man printf,

Trailing zeros are removed from the fractional part of the result; a decimal point appears only if it is followed by at least one digit.

To get a .0 at the end despite the above rule, you would have to do something like print to a temporary string, search it for a decimal point, and retry in fixed mode if not found.

Upvotes: 1

Escualo
Escualo

Reputation: 42152

If you knew in advance whether the number you want to print exhibits a recurring decimal expansion, then you could simply issue an statement along the lines of:

if is_recurring:
    print using expanded format
else
    print using fixed format

I imagine you do not know in advance. And the computer cannot, in general, know it either.

How would it test whether a few decimals (about 15 if you are using double precision) represent a recurring decimal?

Furthermore, how would you like to print it? Take, for instance, the classical example:

3227 / 555 = 5.814414414414414

How should I print it? Like this?

5.8144

or like that?

5.8144
   ***

It seems like a very difficult problem to address in general.

Upvotes: 3

Related Questions