Truncate a decimal value in C++

后端 未结 10 1553
萌比男神i
萌比男神i 2020-12-10 05:38

What\'s the easiest way to truncate a C++ float variable that has a value of 0.6000002 to a value of 0.6000 and store it back in the variable?

10条回答
  •  囚心锁ツ
    2020-12-10 06:00

    Similar to other answers, BUT you must not forget that round, floor and trunc are different by definition. See the definition and output example of the following:

    http://www.cplusplus.com/reference/cmath/trunc/

    In this case we need to trucate with a precision of 4 decimals and get rid of non-significant decimals:

    trunc(valueToTrunc*10000)/10000
    

    or

    value = (double)((int)(valueToTrunc*10000))/(double)10000
    

提交回复
热议问题