How to Round Decimals in C++

C++ is the programming language for writing computer programs of any level of complexity. By default, a C++ program outputs floating-point numbers with many decimal digits. As a result you often have to round such numbers according to the program context. For example, if you write a financial application in C++ you need to print output numbers representing the currency as rounded to the second decimal digit. The C++ standard library (referred as "std" in the code) allows you set the required level of precision to decimal numbers.

Instructions

    • 1

      Declare a variable to test rounding in your C++ program.

      double var1= 2.7749;

    • 2

      Set the fixed presentation of decimal numbers using the following commands:

      std::cout.setf(std::ios:fixed);

      std::cout.setf(std::ios:showpoint);

    • 3

      Set the required precision; for example to round to the third digit after the decimal point use the command:

      std::cout.precision(3);

    • 4

      Print out the rounded variable:

      std::cout <<var1<<std::endl;

      For this example, the program produces the output "2.775" that is the number 2.7749 rounded as requested.

Related Searches:

References

Comments

Related Ads

Featured