Digit limitation from decimal point in C++

后端 未结 8 664
不思量自难忘°
不思量自难忘° 2020-12-28 16:57

I\'m new to C++. I have a double variable double a=0.1239857 and I want to limit variable a from decimal point two digits. So a will b

相关标签:
8条回答
  • 2020-12-28 17:24

    You can set the precision on a stream, e.g.

    double d = 3.14579;
    cout.precision(2);
    cout << d << endl;
    
    // Or use a manipulator
    
    #include <iomanip>
    cout << setprecision(2) << d << endl;
    

    Note that when you send a double or float to a stream like this, it will automatically round for you (which can trip you up sometimes if you aren't aware of this).

    0 讨论(0)
  • 2020-12-28 17:27

    What do you mean by you want to limit the variable ? The value or its formatting. For the value, you can use floor + division. Something like:

    double a = 0.12123
    double b;
    
    b = floor(a * 100) / 100
    
    0 讨论(0)
提交回复
热议问题