Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

setting the number of decimal places

Status
Not open for further replies.

Maurader

Technical User
May 8, 2002
59
CA
Is there a way I can set the number of decimal places in a double?

I need to be able to take two doubles, that are the same up to a certain of decimal places, and compare them only up to that point (so truncate after a certain error level)
 
but that only formats the output stream...i need to do calculations with the truncated number
 
Try this:

#include <iostream.h>
#include <stdio.h>
#include <stdlib.h>
void main()
{
double number;
char buffer[20];
int precval;
int count = 0;
bool counting = false;
int i = 0;
char *pEnd;
cout<<&quot;number = &quot;;
cin>>number;
cout<<&quot;precision value = &quot;;
cin>>precval;
sprintf(buffer,&quot;%lf&quot;, number );
while( buffer != '\0' )
{
if( buffer == '.' )
counting = true;
if( counting )
count++;
if( count == precval + 1 )
break;
i++;
}
buffer[i+1] = '\0';
number = strtod( buffer, &pEnd );
cout<<&quot;number' = &quot;<<number;
}
 
ROUND A NUMBER TO THE NEAREST WHOLE INTEGER
floatValue = floor(floatValue*1+0.5)/1;

ROUND A NUMBER TO THE NEAREST 10th
floatValue = floor(floatValue*10+0.5)/10;

ROUND A NUMBER TO THE NEAREST 100th
floatValue = floor(floatValue*100+0.5)/100;

etc.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top