Shorter than float?

Im trying to do a simple output of position and speed in a program Im working on, but I find that the number of digits it outputs is too long with float, and too short with the short data type (only 1 digit as far as I can see). Ideally, I need a data type that stores four digits, so that my output can be something like

4.235 , 3.141

Is there a simple way of doing this, or will I need to write a function that trims the original data type & puts the numbers directly into a string?
You do not want your variable to be less precise.

What you want is to print your variable in a different way (ie: only print 4 digits, even though the variable itself can contain more)

Example:

1
2
3
4
5
6
7
8
9
10
#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
    float var = 1.234567f;

    cout << setprecision(3) << var << endl; // only print 3 digits
}
1.23
Ah, actually the precision doesnt really matter in this case, since Im passing by value, but no matter

Im actually doing it as inserting it into a string though, how would the above call work in that case?
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <sstream>
#include <iomanip>
#include <iostream>
using namespace std;

string tostr(float num, int precision)
{
    stringstream s;
    s << setprecision(precision) << num;
    return s.str();
}

int main()
{
    float f = 1.23456f;
    string s = tostr(f, 3);
    cout << s;
}
Last edited on
Thanks Disch, that works perfectly :)
Topic archived. No new replies allowed.