Archived

This topic is now archived and is closed to further replies.

wall

Hmmmm

Recommended Posts

Is there a way to decide how many decimals a double or float variable should have. So that if I had a float that has the value 1.18f, I could change the number of decimals to one and the result would be 1.2f. Thanks!

Share this post


Link to post
Share on other sites
this may not be the best way:
  

#include <stdio.h>

#include <stdlib.h>

#include <conio.h>

void main(){
float f = 1.2812f;

char msg[10];
char* stop;

sprintf(msg,"%.2f",f );
f = strtod(msg, &stop );

printf("%f", f );

getch();
}

in sprintf, you can specify precision by %[.number][datatype]

Share this post


Link to post
Share on other sites
another way:

    
// n is the number of decimals

float reduce(float f, int n)
{
unsigned long d;
float fak = 1.0f;

// calculate 10^n

while ( n-- )
fak *= 10.0f;

// upscale and truncate

d = (unsigned long)(f * fak);

// calc. downscale factor

fak = 1.0f/fak;

return (d*fak);
}


Edited by - darookie on February 20, 2002 2:40:13 PM

Share this post


Link to post
Share on other sites
quote:
Original post by wall
Is there a way to decide how many decimals a double or float variable should have. So that if I had a float that has the value 1.18f, I could change the number of decimals to one and the result would be 1.2f.


In what language? If you''re talking about C or C++, then the answer''s no. However, if you think about it, it doesn''t matter what precision a float is when it''s used internally within a program. It''s only when you output it to some device that you will really be concerned with the precision. Then you can use the stream manipulators to control the formatting and precision of the output. For example, C++ iostreams include the manipulators setprecision(), setw(), etc. You might like to look those up.

--
The placement of a donkey''s eyes in its head enables it to see all four feet at all times.

Share this post


Link to post
Share on other sites