How to set 3 digits after comma - c++

Well, basically I was using setprecision(3), but that is rounding up the last number, for example if we do like this -
double x = 5;
x = (double) x / 3;
cout << fixed << setprecision(3) << x << endl;
It will show 1.667
But, if we do it with calculator, it will show - 1.666666666...67
So basically, what I mean is, is there any chance to output in file, just the first 3 digits after the comma, and not to round it up?

1.666666666...67 rounded to three decimal places is 1.667
If you just want to truncate the output then send it to a string with strstream, search the string for the position of "." and truncate the string 3 places beyond that
Or if you simply want to always round down, multiply the result by 1000, use floor() to round down and then divide by 1000.0 again.

A cast to long truncates the fraction part :
int main()
{
double x;
x= -100.666666666666666;
x = static_cast<double> ( static_cast<long>(x * 1000) )/1000;
cout << x << endl;
}
We could use floor(double) from cmath, which is more preferable, but it's rounds negatives to negative side either.

cout << fixed << setprecision(3) << double(int(x*1000))/1000 << endl;
we use int() to truncate the tailing digits.

Related

cout prints inaccurate result and printf prints accurate result

The following code in C++:
double x = 500000.6;
printf("%f\n", x);
cout << x << endl;
prints the following:
500000.600000
500001
Why cout isn't printing the correct value (500000.6)?
Putting the following line as the beginning of the code makes cout prints correct result:
cout.precision(7);
However, setting the precision to 6 (which is the default anyways) doesn't print the expected result.
Why this happen? I have only 1 digit after the decimal point, not 7 digits!
By default, the precision is the total number of significant digits. It's not the number of digits after the decimal point. 500000.6 has seven significant digits, 500001 has only six.
Try this instead
cout << fixed << setprecision(1) << x << endl;
When used for fixed format, the precision is the number of digits after the decimal point.

How to express large numbers to two decimal places in C++ Calculator

I am trying to write a calculator in C++ that does the basic functions of /, *, -, or + and shows the answer to two decimal places (with 0.01 precision).
For example 100.1 * 100.1 should print the result as 10020.01 but instead I get -4e-171. From my understanding this is from overflow, but that's why I chose long double in the first place!
#include <iostream>
#include <iomanip>
using namespace std;
long double getUserInput()
{
cout << "Please enter a number: \n";
long double x;
cin >> x;
return x;
}
char getMathematicalOperation()
{
cout << "Please enter which operator you want "
"(add +, subtract -, multiply *, or divide /): \n";
char o;
cin >> o;
return o;
}
long double calculateResult(long double nX, char o, long double nY)
{
// note: we use the == operator to compare two values to see if they are equal
// we need to use if statements here because there's no direct way
// to convert chOperation into the appropriate operator
if (o == '+') // if user chose addition
return nX + nY; // execute this line
if (o == '-') // if user chose subtraction
return nX - nY; // execute this line
if (o == '*') // if user chose multiplication
return nX * nY; // execute this line
if (o == '/') // if user chose division
return nX / nY; // execute this line
return -1; // default "error" value in case user passed in an invalid chOperation
}
void printResult(long double x)
{
cout << "The answer is: " << setprecision(0.01) << x << "\n";
}
long double calc()
{
// Get first number from user
long double nInput1 = getUserInput();
// Get mathematical operations from user
char o = getMathematicalOperation();
// Get second number from user
long double nInput2 = getUserInput();
// Calculate result and store in temporary variable (for readability/debug-ability)
long double nResult = calculateResult(nInput1, o, nInput2);
// Print result
printResult(nResult);
return 0;
}
setprecision tells it how many decimal places you want as an int so you're actually setting it to setprecision(0) since 0.01 get truncated. In your case you want it set to 2. You should also use std::fixed or you'll get scientific numbers.
void printResult(long double x)
{
cout << "The answer is: " << std::fixed << setprecision(2) << x << "\n";
}
working example
It is not due to overflow you get the strange result. Doubles can easily hold numbers in the range you are showing.
Try to print the result without setprecision.
EDIT:
After trying
long double x = 100.1;
cout << x << endl;
I see that it doesn't work on my Windows system.
So I searched a little and found:
print long double on windows
maybe that is the explanation.
So I tried
long double x = 100.1;
cout << (double)x << endl;
which worked fine.
2nd EDIT:
Also see this link provided by Raphael
http://oldwiki.mingw.org/index.php/long%20double
The default floating point presentation switches automatically between presentation like 314.15 and 3.1e2, depending on the size of the number and the maximum number of digits it can use. With this presentation the precision is the maximum number of digits. By default it's 6.
You can either increase the maximum number of digits so that your result can be presented like 314.15, or you can force such fixed point notation by using the std::fixed manipulator. With std::fixed the precision is the number of decimals.
However, with std::fixed very large and very small numbers may be pretty unreadable.
The setprecision() manipulator specifies the number of digits after the decimal point. So, if you want 100.01 to be printed, use setprecision(2).
When you use setprecision(0.01), the value 0.01 is being converted to int, which will have a value of 0.
It wouldn't have hurt if you had actually read the documentation for setprecision() - that clearly specifies an int argument, not a floating point one.

C++ Money Class - storing and rounding cents

thanks in advance.
I'm writing a C++ assignment for class where we're creating our own money/currency class. I'm having trouble figuring out why my passing of a float isn't giving me enough precision.
Implementation:
private:
long int DOLLARS;
short int CENTS;
Currency::Currency(float tmpMoney)
{
// cout << "tmpMoney is: " << tmpMoney << endl;
int tmpDollar;
float tmpCent;
tmpDollar = static_cast<int>(tmpMoney);
tmpCent = (tmpMoney-tmpDollar)*100;
DOLLARS = tmpDollar;
CENTS = tmpCent;
}
Main Program:
Currency c1(2342.59);
Currency c2(2342.515); // there is no half cent coin, round it to 2342.52
If I output 'tmpMoney' it just gives me (for c2) 2345.51.
I'm not sure how to round .515 if the value doesn't even go that far.
It's a bad idea to make a currency type be constructible from floating-point type.
7 decimal digits is in general beyond float precision. You can still get desired output by:
float tmpMoney = 2342.515;
cout << setprecision(7) << tmpMoney << endl;
// 2342.515
But the internal representation is far from perfect:
cout << setprecision(10) << tmpMoney << endl;
// 2342.514893
If the number is large enough, you'll lose more:
float tmpMoney = 123456789.12;
cout << setprecision(12) << tmpMoney << endl;
// 123456792
So you may decide to use double instead, but you should be really careful because for large enough numbers you'll get the same errors:
double tmpMoney = 3333333333333333.42; // 17 digits
cout << setprecision(18) << tmpMoney << endl;
// 3333333333333333.5
If there is a chance that you'll have such numbers, don't initialize Currency with double either.
I would advise you to have just a constructor like Currency(int dollars, int cents).
You can also check this question for some insights.
#include <cmath>
CENTS = round(tmpCent);
Due to floating point representation, this may not always give the right result. The closest you can get is have a margin of error epsilon, say
#define EPS 0.000001
then you can do
CENTS = round(tmpCent + EPS);
Note that this will accept values that are represented as 0.499999 <= x < 0.5
And it's preferable to use double and not float to keep the precision as close as possible.

How to +1 to the digit if the first decimal is greater than or equal to 5?

My goal is to add the value in front of my decimal place when the first decimal places is more than or equal to 5.
For example:
#include <iostream>
using namespace std;
int main()
{
float num = 0.5222f;
cout << (int)num << endl;
cin.get();
return 0;
}
My intended result is 1 instead of 0. How should I modify the code to get the expected result?
If you want to round this value to the nearest integer, you could just add 0.5 before casting it to int:
float num = 0.5222f;
cout << (int)(num + 0.5);
or alternatively you might use one of the following functions from the <cmath> header:
double round (double x);
float roundf (float x);
long double roundl (long double x);
In C++11 we now have std::round, so this would work fine:
std::cout << std::round(num) << std::endl;
would also need to include <cmath>. The non-C++11 method using floor:
std::cout << floor(num + 0.5) << std::endl;
If you cast a float to an int it rounds towards zero, dropping the fractional portion of the number.
What you want to do is call roundf first. (round for double, roundf for float)
cout << (int)roundf(num) << endl;
I just add:
float num = 0.5222f;
cout << std::floor(num + 0.5);
In this way you can even decide to round up also if (say) first digit is > 3
float num = 0.3222f;
cout << std::floor(num + 0.7);
Don't know how much useful, but.... you can!
Try the ceil function.
It rounds up numbers of 0.5 to a whole decimal number by 1.
http://en.cppreference.com/w/cpp/numeric/math/ceil

c++ how to obtain randon numbers and how to save a double with ony two decimals?

I have the following :
int R=25;
double pi=3.14;
double r=R*sqrt(rand());
cout<<"r: "<<r<<endl;
double th=2*pi*rand();
cout<<"th: "<<theta<<endl;
I want to convert : r=1.98 and th=5.08. I would also like the double result=r*th to be with 2 zecimals.
when I print double result =r*th; the number is very huge and is not realistic.
How to change the r and th value to 1.98 and 5.08? How to solve this?
I need to change each double to just 2 decimals after "."
I am working in c++ under ubuntu.
Thx appreciate
To produce random values in the range you specified, try this:
r = (R*(rand()/(RAND_MAX + 1.0)));
th = (2*3.14*(rand()/(RAND_MAX + 1.0)));
The expression rand()/(RAND_MAX+1.0) produces values in the range [0,1.0). Multiplying that by the range limit gives you the numbers you want.
Note: this doesn't limit the numbers to two decimal places, which is more a function of how you print them. To print them with two decimal places, try this:
std::cout << std::fixed << std::setprecision(2) << r << "\n";
std::cout << std::fixed << std::setprecision(2) << th << "\n";
std::cout << std::fixed << std::setprecision(2) << (r*th) << "\n";
See this question: C++ generating random numbers
If you need to make both numbers smaller by the same amount then you can simply divide them both by the same number. You'll lose approximately the same precision either way.
If you really want to completely alter the result by chopping off the exponent then you could probably dig into the double number format itself and separate out the mantissa.
Why you would do this is a mystery to me.