Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display a fixed number of digits in C++ without rounding

I have this code (very basic):

#include <iostream>
#include <iomanip>

using namespace std;
int main()
{
float   a = 0.0,
        b = 0.0,
        c = 0.0;

cout<<"Input a: ";
cin>>a;
cout<<"input b: ";
cin>>b;
cout<<endl;
c = a / b;

cout<<"Result: "<<fixed<<setprecision(2)<<c<<endl;
return 0;
}

When I enter two numbers (say, a = 513 and b = 791) I get 0.65. Calculator shows that the correct answer is 0.648. I understand that my code rounds up the last decimal number but this is not what I want.

How can I get it to where it just stays as 0.64 and not 0.65?

like image 507
user2529011 Avatar asked Nov 03 '13 22:11

user2529011


People also ask

How do I stop printf from rounding?

Printf is supposed to round it. To prevent this, truncate the argument to 4 decimal places. You could sprintf() into a temp buffer for 5 decimal places and then lop off the last digit. Or, you could multiply the source number by 10,000, cast it to an int, and then back to a float and divide by 10,000.

How do I print float numbers upto 1 decimal C?

Use "%. By using this format specifier we can print specific number of digits after the decimal, here "n" is the number of digits after decimal point. Consider the program, here we will print 2 digits after the decimal point. Here, we are using "%.

How do I truncate decimal places?

To truncate a number to 1 decimal place, miss off all the digits after the first decimal place. To truncate a number to 2 decimal places, miss off all the digits after the second decimal place.

How do you write decimal numbers in C?

For example, 5.48958123 should be printed as 5.4895 if given precision is 4. In C, there is a format specifier in C. To print 4 digits after dot, we can use 0.4f in printf(). Below is program to demonstrate the same.


2 Answers

If you would like to truncate the value to two decimal places, you can multiply it by 100, truncate to integer, and then divide by 100, like this:

c = a / b;
c = floor(100 * c) / 100;
cout<<"Result: "<<fixed<<setprecision(2)<<c<<endl;

Demo on ideone.

like image 54
Sergey Kalinichenko Avatar answered Nov 07 '22 19:11

Sergey Kalinichenko


You can use trunc to truncate to a certain number of digits:

c = a / b;

// truncate past two decimals:
c = trunc(c * 100) / 100;

cout<<"Result: "<<fixed<<setprecision(2)<<c<<endl;

of for a generic function:

int trunc(double val, int digits)
{
    double pow10 = pow(10,digits);
    return trunc(val * pow10) / pow10;
}

then use

cout << "Result: " << fixed << setprecision(2) << trunc(c,2) << endl;
like image 26
D Stanley Avatar answered Nov 07 '22 21:11

D Stanley