1

I have a float number ranging from 0.001 up to 999.999 The question: how I can format all the range numbers like this:

0.001 becomes 000.001

0.002 becomes 000.002

0.2 becomes 000.200

1.001 becoes 001.001

9.090 becomes 009.090

99.100 becomes 099.100

Thanks

Jeremy Friesner
  • 70,199
  • 15
  • 131
  • 234
Nadir
  • 55
  • 6

3 Answers3

4

Please inspect documentation of of stream manipulators.

There couple tools which will let you do it:

    while (std::cin >> x) {
        std::cout 
            << std::setfill('0') << std::setw(7) 
            << std::fixed << std::setprecision(3)
            << x << '\n';
    }
  • std::fixed forces fixed format (decimal separator in same place)
  • std::setprecision(3) defines how many digits should be after a decimal separator.
  • std::setw(7) - defines minimum space number should occupy
  • std::setfill('0') defines what should be used to fill extra space introduced by std::setw(7).

https://godbolt.org/z/zf6q8n97r

Extra note:

C++20 introduces nice type safe and clean equivalent of printf from C: format, but there is no compiler which already supports that.

Marek R
  • 32,568
  • 6
  • 55
  • 140
0

With std::printf:

#include <cstdio>

int main(void)
{
    float f = 99.01f;
    std::printf("%07.03f", f);
}

07 specifies that if the number takes up less space than 7 characters it'll be padded with leading 0s while 03 specifies that the if the numbers after the decimal point take up less space than 3 characters then it'll be padded with trailing 0s.

As of C++20 you can use similar formatting in std::format:

std::cout << std::format("{:07.03f}", f);
mediocrevegetable1
  • 4,086
  • 1
  • 11
  • 33
0

use std stream formatters from iomanip. Stop using printf : Why not use printf() in C++

#include <iostream>
#include <iomanip>
#include <vector>


int main()
{
    std::vector<double> values{ 0.001, 0.002, 0.2, 1.001, 9.090, 99.100 };

    for (const auto value : values)
    {
        std::cout << std::fixed;
        std::cout << std::setprecision(3);
        std::cout << std::setfill('0') << std::setw(7);
        std::cout << value << std::endl;
    }

    return 0;
}
Pepijn Kramer
  • 9,356
  • 2
  • 8
  • 19