#### Archived

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

# Hmmmm

This topic is 5992 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## 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 on other sites
this may not be the best way:
  #include #include #include 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 on other sites
another way:

  // n is the number of decimalsfloat 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 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.

1. 1
Rutin
23
2. 2
3. 3
JoeJ
20
4. 4
5. 5

• 29
• 40
• 23
• 13
• 13
• ### Forum Statistics

• Total Topics
631740
• Total Posts
3001965
×