Truncate a decimal value in C++

后端 未结 10 1730
萌比男神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 05:51

    Realistically that's not possible. It's not a C++ limitation, but just the way floating point works. For many values there are no precise representations, so you can't simply truncate to a number of digits.

    You could truncate when printing using printf format strings.

    If you really need to be able to store only a limited number of digits, I suggest you use a fixed-precision data type instead.

提交回复
热议问题