Convert a double to fixed decimal point in C++

前端 未结 4 1343
忘了有多久
忘了有多久 2021-01-18 12:03

I have a double variable in C++ and want to print it out to the screen as a fixed decimal point number.

Basically I want to know how to write a function that takes a

相关标签:
4条回答
  • 2021-01-18 12:18

    Look at the setprecision manipulator which should give you the idea

    0 讨论(0)
  • 2021-01-18 12:18
    #include <iomanip>
    #include <iostream.h>
    
    // print a float, x places of precision 
    void convert (double number, int x)
    {
        cout << setprecision(x) << number << endl;
    }
    
    int main()
    {
        double a = 1.234;
        convert (a,2);
    } 
    

    output: 1.23

    reference

    0 讨论(0)
  • 2021-01-18 12:21

    Assuming I'm remembering my format strings correctly,

    printf("%.*f", (int)precision, (double)number);
    
    0 讨论(0)
  • 2021-01-18 12:35

    There is no such thing as a "fixed decimal place" number. The convert function will need to be the function that actually prints it out. I would suggest getting the whole part of the number, then print it. If [decimal places]>0 then print a decimal place, then print each decimal individually like: floor((n*log(10,d))%10); <-- just an idea, not actual code.

    0 讨论(0)
提交回复
热议问题