Digit limitation from decimal point in C++

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

提交回复
热议问题