Click here to Skip to main content
15,891,905 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
How do you fix a float so that it only displays as 3 numbers?

example

xx.x

13.4

even when the float is 13.4355667.
Posted

You know when you format a string so that is displays a float, like so:
char buff[32];
float number = 1.23456789f;
sprintf_s(buff, 32, "My Number: %f", number);


You can specify the number of decimals to print after the point by using %.2f for two decimal places and %.8f for eight places and so on.

I'm not sure there's any built in formatting to limit the number of significant digits though. So 1234567 would become 123e4 and 0.00015678 would become 0.000157 if you wanted 3 significant digits. But you do have some easy control over the number of decimal places.

EDIT: If you're using cout then to limit the number of decimal places you'd need to do this:

#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
  float num = 1.23456f;
  cout << "My Number: " << setprecision(1) << num;

  return 0;
}


Where the output would then be "My Number: 1.2"

The number you pass to setprecision is the number of decimal places you want.
 
Share this answer
 
v4
Comments
WurmInfinity 11-Nov-10 11:49am    
Ok thats awesome thats pretty much what I wanted. Urrm one question though my floats not static its cin << so would it be just.
float money ;
cin << money;
(person puts in 3.45673)
cout << "Money comes to: "; cout << money %.3f;
I don't really know :S sorry im a begginer :(
Anthony Mushrow 11-Nov-10 12:00pm    
If you're using cout then you need to use setprecision to specify the number of decimal places you want.
float num = 1.23456f;
cout << "My Number: " << setprecision(1) << num;
WurmInfinity 11-Nov-10 12:11pm    
cout << "Ceiling: "; cout << setprecision(3) << (ceilingArea/8)*3.50;

Just getting a undeclared error for setprecision :(
Anthony Mushrow 11-Nov-10 12:21pm    
Sorry, forgot to encode my < > for the includes in my update. You need to add #include <iomanip>
WurmInfinity 11-Nov-10 12:25pm    
WOOP it worked. I love you right now, been bothering me all day. Thanks so much dude.
Don't use floats (or doubles) for monetary values as they can lose precision in calculations. You should use integers representing the smallest value of the currency (pence, cents etc).
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900