Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display numbers with padding and a fixed number of digits in C++

I'd like to display numbers using a padding (if necessary) and a fixed number of digits. For instance, given the following numbers:

48.3
0.3485
5.2

Display them like this:

48.30
00.35
05.20

I'm trying combinations of std::fixed, std::fill, std::setw, and std::setprecision, but I can't seem to get what I'm looking for. Would love some guidance!

NOTE: The 0-padding isn't really critical, but I'd still like the numbers to be aligned such that the decimal point is in the same column.

like image 231
aardvarkk Avatar asked Sep 18 '25 09:09

aardvarkk


1 Answers

It's pretty straightforward

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

int main()
{
    cout << fixed << setprecision(2) << setfill('0');
    cout << setw(5) << 48.3 << endl;
    cout << setw(5) << 0.3485 << endl;
    cout << setw(5) << 5.2 << endl;
}

Writing code like this makes me yearn for printf however.

like image 188
john Avatar answered Sep 20 '25 01:09

john