2

I would like to print floating point numbers in a format like this.

01234.56

I use the following function to round a float to n digits.

double round(double val, int precision)
{
    std::stringstream s;
    s << std::setprecision(precision) << std::setiosflags(std::ios_base::fixed) << val;
    s >> val;
    return val;
}

And the following line to output any number with leading zeroes to a fixed length.

setfill ('0') << setw(5) << number

But when I try to combine the two, I end up with non-consistent length, like in the following examples:

8.2 => 008.2
4.57 => 04.56

What I would like to have is an output like this:

8.2 => 08.20
4.57 => 04.57

Can you show me a function like string myround (double d, intpart n, floatpart f) which returns:

myround (1234.5, 5, 2) => 01234.50
myround (1234.569, 5, 2) => 01234.57

I imageine it has been asked before, but I couldn't find it using the internal search engine.

1 Answer 1

2

the fixed manipulator will do the trick I think, my example below outputs what you wanted:

#include <iostream>
#include <iomanip>
using namespace std;
int main(void) {
    cout << setprecision(2) << setfill ('0') << setw(5) << fixed << 8.2 << endl;
    cout << setprecision(2) << setfill ('0') << setw(5) << fixed << 4.57 << endl;
}

just put it into your stringstream and it should work. However, the fixed information will be lost when the string is converted to a double value again. I think it is no good idea to round a float using a string method.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.