How to separate whole number and decimal number to two different variable - c++

I am trying to separate whole number and decimal number
two int variable
#include <iostream>
#include <iomanip>
#include<math.h>
using namespace std;
int main()
{
double initialAmount = 42800.13;
double fractionalPart = initialAmount - floor(initialAmount);
cout<<int(initialAmount)<<"\n"<<fractionalPart<<"\n";
}
Present output is
42800
0.13
expected output
42800
13
It can be more than two decimal places .
any easy way to do that

Maybe not the best solution, but at least it is simple :)
Store your double initialAmount in a int - which will truncate the decimal part. Then you have the number before the decimal point. Then subtract that from the initial value and you'll be left with just the part after the decimal point. Multiply that by however many powers of 10 that you deem significant and then again store that in a int and you'll have your two values.

As suggested in the comments, it could help to convert the number into a string. Here's one possibility:
#include <sstream>
#include <iostream>
#include <vector>
#include <string>
int main() {
double d = 42800.13;
std::vector<std::string> numbers_s;
std::string s;
std::istringstream numberAsString(std::to_string( d ));
while (getline(numberAsString, s, '.')) {
numbers_s.push_back(s);
}
std::cout << "whole number:" << numbers_s[0] << std::endl;
//[ remove trailing zeros from fractional part:
numbers_s[1].erase(numbers_s[1].find_last_not_of('0') + 1, std::string::npos);
//]
std::cout << "fractional part:" << std::stoi(numbers_s[1]) << std::endl;
}
Error checks should be added to capture cases when the number does not contain a decimal point.

Related

C++ decimal placement

how would I make it so when i enter 2.785 for the input question the output will display the variable question as 2.79?
I tried using setprecision but for some reason it is not working unless i am doing it wrong
here is the user input question and what it should be:
Enter positive daily growth % (.1 must be entered as 10):
user enters "2.785"
output -> 0.02785
My desired output should look like:
desired output-> 2.79%
Any help is appreciated. I know it may seem simple to others but I have already tried looking online and everything I find just isn't making sense or doesn't work and I dont know what I am doing wrong.
Floating point arithmetic
The reason why it is challenging is that floating point cannot be represented accurately when you perform operations on them. See wikipedia article
It is a very intesting topic, if you have a bit of time, take a look at explanations about floating point and how its representation inside the computer.
If you are looking for the display only (only works for small decimals)
If you are just looking to display a small value you can use below code:
#include <cmath>
#include <iostream>
#include <iomanip>
#include <limits>
#include <sstream>
using namespace std;
string truncateAsString(double n, int precision) {
stringstream ss;
double remainder = static_cast<double>((int)floor((n - floor(n)) * precision) % precision);
ss << setprecision(numeric_limits<double> ::max_digits10 + __builtin_ctz(precision))<< floor(n);
if (remainder)
ss << "." << remainder;
cout << ss.str() << "%" << endl;
return ss.str();
}
int main(void) {
double a = 0.02785;
int precision = 100; // as many digits as you add zeroes. 3 zeroes means precision of 3.
string s = truncateAsString(a*100 + 0.5 / 100, precision);
return 0;
}
Looking for the true value?
Maybe you are looking for true value for your floating point, you can use boost multiprecision library
The Boost.Multiprecision library can be used for computations requiring precision exceeding that of standard built-in types such as float, double and long double. For extended-precision calculations, Boost.Multiprecision supplies a template data type called cpp_dec_float. The number of decimal digits of precision is fixed at compile-time via template parameter.
You need to use a custom library like boost/multiprecision because of the lack of precision for floating points, see my code below:
#include <boost/math/constants/constants.hpp>
#include <boost/multiprecision/cpp_dec_float.hpp>
#include <iostream>
#include <limits>
#include <cmath>
#include <iomanip>
using namespace std;
using boost::multiprecision::cpp_dec_float_50;
cpp_dec_float_50 truncate(cpp_dec_float_50 n, int precision) {
cpp_dec_float_50 remainder = static_cast<cpp_dec_float_50>((int)floor((n - floor(n)) * precision) % precision) / static_cast<cpp_dec_float_50>(precision);
return floor(n) + remainder;
}
int main(void) {
int precision = 100; // as many digits as you add zeroes. 5 zeroes means precision of 5.
cpp_dec_float_50 n = 0.02785 * 100;
n = truncate(n + 0.5/precision, precision); // first part is remainder, floor(n) is int value truncated.
cout << setprecision(numeric_limits<cpp_dec_float_50> ::max_digits10 + __builtin_ctz(precision)) << n << "%" << endl; // __builtin_ctz(precision) will equal the number of trailing 0, exactly the precision we need!
return 0;
}
Output (both cases)
2.79%
NB: I add 0.5 / precision to the truncate function to force it to act like a rounding.

set precision as per the numer of digits after decimal point c++

I have a code where i can get digit upto 9 digits after decimal point so say something like 0.123456789. Now we can have a case where i get the value 10.123 or say 1001.12. Now there are only 3 digits after decimal point and 2 digits in e.g 10.123 and 1001.12. I am using
#include <iostream>
#include <iomanip>
#include <sstream>
#include <stdio.h>
using namespace std;
int main()
{
std:stringstream ss;
double val = 1.234;
ss.str(std::string());
ss << std::fixed;
ss << std::setprecision(9);
ss << val;
string number= ss.str();
std::cout << number <<"\n";
return 0;
}
Above would give output as 1.234000000 . Note that i would want the precision to be handled automatically depending on the length of the digits after decimal point. One way is for me to find number of digits after decimal point and set precision evverytime , is there some other standard method provided, that takes care of it ?
Thanks

how to print specific number of digits in c++?For example ,printing 8 digits totally(before+after decimal point combined)

how to print specific number of digits in c++?For example ,printing 8 digits totally(before and after decimal point combined)
Edit: For further clarification, setprecision sets the digits when i have decimal digits to display.I want to display integer 30 also as 30.000000 ,in 8 digits.
The setprecision command puts fixed no. of digits after decimal and i don't want that.
In short , I want an alternative of c command printf("%8d",N) in C++.
You can do it using setprecision() function from include iomanip and fixed like:
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
double d = 1000;
double t = d;
int dc=0;
while(t>0.9)
{
dc++;
t= t/10;
}
cout<<"dc:"<<dc<<endl;
cout << fixed;
std::cout << std::setprecision(dc);
std::cout << d;
return 0;
}
The setprecision() will not work fine every time So you have to use fixed as well.
You should use the c++ header iomanip what you want is the setprecision() function:
std::cout << std::setprecision(5) << 12.3456789 << std::endl;
outputs 12.346. It also has other modifiers you can find here
EDIT
If you want to print trailing 0s, you need to also use std::fixed. This says to use that number of digits, regardless of whether or not they are significant. If you want that to be the total number, you could figure out the size of the number, then change the precision you set it to based on that, so something like:
#include <iostream>
#include <iomanip>
#include <cmath>
int main()
{
double input = 30;
int magnitude = 0;
while(input / pow(10, magnitude))
{
++magnitude;
}
std::cout << std::fixed << std::setprecision(8 - magnitude) << input << std::endl;
return 0;
}
This returns 30.000000. You can also do something similar by outputting to a string, then displaying that string.

New to C++: having issues maintaining trailing zeros on a decimal value [duplicate]

I see many questions about the precision number for floating point numbers but specifically I want to know why this code
#include <iostream>
#include <stdlib.h>
int main()
{
int a = 5;
int b = 10;
std::cout.precision(4);
std::cout << (float)a/(float)b << "\n";
return 0;
}
shows 0.5? I expect to see 0.5000.
Is it because of the original integer data types?
#include <iostream>
#include <stdlib.h>
#include <iomanip>
int main()
{
int a = 5;
int b = 10;
std::cout << std::fixed;
std::cout << std::setprecision(4);
std::cout << (float)a/(float)b << "\n";
return 0;
}
You need to pass std::fixed manipulator to cout in order to show trailing zeroes.
std::cout.precision(4); tells the maximum number of digits to use not the minimum.
that means, for example, if you use
precision 4 on 1.23456 you get 1.235
precision 5 on 1.23456 you get 1.2346
If you want to get n digits at all times you would have to use std::fixed.
The behavior is correct. The argument specifies the maximum meaningful amount of digits to use. It is not a minimum. If only zeroes follow, they are not printed because zeroes at the end of a decimal part are not meaningful. If you want the zeroes printed, then you need to set appropriate flags:
std::cout.setf(std::ios::fixed, std::ios::floatfield);
This sets the notation to "fixed", which prints all digits.

C++ String to double conversion using stringstream gives precision error

This is a snippet of my code. I need some help in removing the error shown below.
#include <iostream>
#include <string>
#include <sstream>
int main()
{
char doubleStr[] = "5.2";
double d = 0.0;
std::stringstream stream (doubleStr);
stream >> d;
std::cout << d << std::endl;
std::cout << (d <= 5.2);
return 0;
}
This gives output:
5.200000000002
0
How to remove this precision error? Can I use std::setprecision() to solve the issue?
numeric_limits<double>::digits10 can be used to find the number of digits that are uniquely representable by a double.
I see you've tagged your question with Visual Studio. You can test this code on http://webcompiler.cloudapp.net/ to get Visual Studio's number of uniquely representable digits for a double:
#include <iostream>
#include <limits>
int main() { std::cout << std::numeric_limits<double>::digits10 << std::endl; }
This code will not output 2 it will output:
15
Which means that any double up to 14 decimal places will survive the round trip through a stringstream and still be equal to itself.
The above means that there is something you are not including in your example that is causing the round trip failure, or you are using non-standard source files that are not IEEE compliant. (For example I can do a live example on gcc that gives a contrary output to yours, and running the same code on Visual Studio disagrees with your output.)
Either way, for any uniquely representable double (like 5.2), you can ensure that round trip success through a stringstream by setting the precision. Precision is a sticky modifier, so you'll only need to set it once after stream construction. In your example you use stringstream stream so before you work with stream you'd need to set this modifier:
stream.precision(numeric_limits<double>::digits10 - 1);
You can use it like this in order to show the double number in the right way:
#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>
#include <cmath>
#include <limits>
int main()
{
char doubleStr[] = "5.2";
double d = 0.0;
std::stringstream stream (doubleStr);
stream >> d;
std::cout << std::setprecision(2)<< d << std::endl;
return 0;
}
http://cpp.sh/9lub
about comparing float point numbers you may look at this What is the most effective way for float and double comparison?