Truncate a decimal value in C++

后端 未结 10 1555
萌比男神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
    
    0 讨论(0)
  • 2020-12-10 06:04

    A good reference for why this happens can be found in What Every Computer Scientist Should Know About Floating Point Arithmetic by David Goldberg.

    0 讨论(0)
  • 2020-12-10 06:06

    Here is a function using the advice in other answers and an example of its use:

    #include <iostream>
    #include <cmath>
    
    static void Truncate(double& d, unsigned int numberOfDecimalsToKeep);
    
    int main(int, char*[])
    {
    
      double a = 1.23456789;
      unsigned int numDigits = 3;
    
      std::cout << a << std::endl;
    
      Truncate(a,3);
    
      std::cout << a << std::endl;
    
      return 0;
    }
    
    void Truncate(double& d, unsigned int numberOfDecimalsToKeep)
    {
        d = roundf(d * powf(10, numberOfDecimalsToKeep)) / powf(10, numberOfDecimalsToKeep);
    }
    
    0 讨论(0)
  • 2020-12-10 06:07

    you can use this:

    int n = 1.12378;
    cout << fixed << setprecision(4) << n;
    

    the output will be: 1.1238

    not: 1.1237

    it just sea the last decimal number not all: 12.123447 ==> 12.1234

    be careful about that...

    0 讨论(0)
提交回复
热议问题