Truncate a decimal value in C++

后端 未结 10 1729
萌比男神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:56

    roundf(myfloat * powf(10, numDigits)) / powf(10, numDigits);
    

    For example, in your case you're truncating three digits (numDigits). You'd use:

    roundf(0.6000002 * 1000) / 1000
    // And thus:
    roundf(600.0002) / 1000
    600 / 1000
    0.6
    

    (You'd probably store the result of powf somewhere, since you're using it twice.)

    Due to how floats are normally stored on computers, there'd probably be inaccuracies. That's what you get for using floats, though.

提交回复
热议问题