delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1999/03/08/03:59:09

Date: Mon, 8 Mar 1999 10:55:54 +0200 (IST)
From: Eli Zaretskii <eliz AT is DOT elta DOT co DOT il>
X-Sender: eliz AT is
To: Victor Senderov <victor DOT bg AT usa DOT net>
cc: djgpp AT delorie DOT com
Subject: Re: Problem with floats
In-Reply-To: <36E32739.E6E9AFA0@usa.net>
Message-ID: <Pine.SUN.3.91.990308105534.23421M-100000@is>
MIME-Version: 1.0
Reply-To: djgpp AT delorie DOT com
X-Mailing-List: djgpp AT delorie DOT com
X-Unsubscribes-To: listserv AT delorie DOT com

On Sun, 7 Mar 1999, Victor Senderov wrote:

> #include <iomanip.h>
> #include <iostream.h>
> int main()
> {
>  cout << setprecision(25);
>  double test = 37000.95000;
>  cout << test;
>  return 0;
> }
> 
> Output : 37000.94999999999708961695
> Can anybody explain why it outputs something so incorrect?

The double data type has a precision of about 16 decimal digits.  In
your case, the first incorrect digit (the 7 after the string of 9's)
is in 17th place counting from the beginning of the number.  So this
result is okay.

The problem is in your program: you shouldn't request 25-digit
precision in the first place, because you can't get it.  Ask for
16-digit (or less) precision, and the printed result will be what
you'd expect.

If you need more digits, use the long double type instead; it has
19-digit accuracy.

> Also, I
> compiled this under other compiler and it worked ok -- the other
> compiler displayed 37000.95

It depends on the fine details of how a compiler and the library
convert numbers to strings and back.

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019