Digit limitation from decimal point in C++

后端 未结 8 663
不思量自难忘°
不思量自难忘° 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:04

    If you just want to output the value, you can do something like

    printf("%.3f", a); // Output value with 3 digits after comma
    

    If you want to convert the value itself, you can do:

    a = (int)(a * 1000) / 1000.0f;
    

    Note that both do no rounding, they just truncate the value.

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

    you could also do something like this:

    //This code will ask the user for an input, set the decimal precision to the hundredths place,  and add 4.63 to the inputted variable
    
    int banana;
    cin >> banana;
    cout << setprecision(2) << fixed << banana + 4.63; 
    
    0 讨论(0)
  • 2020-12-28 17:11

    Use a ios_base::precision for formatting i/o.

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

    Are you actually trying to round the number, or just change its displayed precision?

    For the former (truncating the extra digits):

    double scale = 0.01;  // i.e. round to nearest one-hundreth
    value = (int)(value / scale) * scale;
    

    or (rounding up/down as appropriate, per jheriko's answer)

    double scale = 0.01;  // i.e. round to nearest one-hundreth
    value = floor(value / scale + 0.5) * scale;
    

    For the latter:

    cout << setprecision(2) << value;
    

    where the parameter to setprecision() is the maximum number of digits to show after the decimal point.

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

    An actual rounding solution would be x = floor(100*x + 0.5) / 100; assuming the value to be rounded is in a variable "x".

    The x = floor(100*x) / 100; recommended by others here will actually truncate the number to 2dp instead.

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

    This will result in two digits after the decimal place.

    a = floor(a * 100.0) / 100.0;
    
    0 讨论(0)
提交回复
热议问题