Home > Blockchain >  Decimal point of a float
Decimal point of a float

Time:01-02

I am still quite new in the C business. I want to output a float number with only one decimal number. At first I thought it would work with Modulo (%), but I quickly discarded this. Then I wanted to solve it calculated, but I couldn't solve this. There is also a clue. I can only use <iostream> and <fstream>. But now I came across the function setprecision().

My output code is. cout<<fixed<<setprecision(2)<<variable<<endl; However, it outputs e.g. 2.99. I need 2.9 though. cout<<fixed<<setprecision(1)<<variable<<endl; Outputs 3.0, though.

Please help me, I will be infinitely grateful. :)

CodePudding user response:

Illustrating the floating-point environment solution from Sebastian in the comments

#include <fenv.h>
#include <iostream>
#include <iomanip>

int main() {
    if (fesetround(FE_TOWARDZERO)) {
        // need to check for non-zero error condition
        std::cerr << "Unable to set correct rounding direction" << std::endl;
        return 1;
    }

    float value = 2.99f;

    std::cout << std::setprecision(2) << value << std::endl;
}

This prints

2.9

Note that this will also affect other floating point calculations, which may cause unexpected results.

I don't know how widespread support is for these different rounding directions on different target architectures, so if you want extreme portability you'll need to provide a back up solution if fesetround returns a non-zero value.

godbolt

CodePudding user response:

Here's one way:

#include <math.h>
#include <iostream>

int main() {

    auto f = 2.9999;

    std::cout << trunc(f * 10) / 10 << '\n';

}

CodePudding user response:

Sebastian solved it in the comments.

cout<< fixed<<setprecision(1)<<variable-.05<<endl;

Thank you all for contributing. I'll try to improve my

  • Related