Removing some digits after decimal point in C++ - c++

I need to remove digits after decimal points but not all.
For Example, double dig=3.1459038585 i need to convert it to dig=3.14
I think i need to multiple dig to 100 then convert it to integer and then again convert to double and delete to 100 (All this will be 1 line). But is there any function to do this faster?

Any function that implements this functionality will be more flexible, and as such slower by definition. So yes, just write this:
double truncated = (double)((int)dig*100)/100;
It's all CPU-native operations any way so it'll barely cost any clock cycles, especially if inlined or used as a macro.

#include <cmath>
#include <iostream>
int main()
{
double d = 3.1459038585;
std::cout << std::floor(d * 100.) / 100. << std::endl;
}

Related

Store float with exactly 2 decimal places in C++

I would like to take a decimal or non-decimal value and store it as a string with exactly 2 decimal places in C++. I want to do this to show it as a monetary value, so it is always $10.50 or $10.00 rather than $10.5 or $10.
I don't just want to print this, I want to store it, so I don't believe setprecision will work here. I'm doing this in a Qt application, so if there is a way to do it using Qt I can use that as well.
For example:
int cents = 1000;
std::string dollars; //should get value from cents formatted to 10.00
UPDATE:
It seems I don't have the vocabulary yet as I am just beginning to learn C++ to articulate what I am trying to do. Here is what I want to do using Python:
str_money = '$ {:.2f}'.format(num)
In this example, num can be a decimal or not (10 or 10.5 for example) and str_money is a variable that is assigned the value of num as a decimal with exactly 2 numbers after the decimal (in this example, str_money would become 10.00 or 10.50). I want it to store this in a string variable, and I don't need it to store the '$' with the value.
Can I do this in C++?
Your decision to store monetary amounts as integer number of cents is a wise one, because floating-point data types (such as float or double) are generally deemed unsuitable for dealing with money.
Also, you were almost there by finding std::setprecision. However, it needs to be combined with std::fixed to have the expected effect (because std::setprecision means different things depending on which format option is used: the default, scientific or fixed).
Finally, to store the formatting result in an std::string instead of directly printing it to the console, you can use a string-based output stream std::ostringstream. Here is an example:
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
std::string cents_to_dollars_string(const int cents)
{
static constexpr double cents_per_dollar{ 100. };
static constexpr int decimal_places{ 2 };
std::ostringstream oss;
oss << std::fixed << std::setprecision(decimal_places) << cents / cents_per_dollar;
return oss.str();
}
int main()
{
const int balance_in_cents{ -420 };
const std::string balance_in_dollars{ cents_to_dollars_string(balance_in_cents) };
std::cout << "Your balance is " << balance_in_dollars << '\n';
}
Here, we first define the function cents_to_dollars_string, which takes the amount in cents as an int and returns an std::string containing the formatted amount of dollars. Then, in main we call this function to convert an amount (in cents) stored in an int variable balance_in_cents to a string and store it into an std::string variable balance_in_dollars. Finally, we print the balance_in_dollars variable to the console.
If you want to store a fixed number of decimal places, a float is not what you want. You want a fixed-point number. With money, the basic idea is to store the value as "cents" in an integer. Then you can perform a division by 100 whenever you want to output the value as "dollars". (Or have a custom output function or operator that formats the output correctly.)
One of the big benefits to fixed-point arithmetic is that you can avoid rounding errors. Floating point numbers are really bad at exactly storing decimal fractions, so dealing with "tenths" or "hundredths" can easily result in rounding errors that can add up in long running, or complicated programs.
How you implement your fixed point numbers is largely up to you. You might find a library that has a fixed-point class, you could implement your own, or you could just manipulate integer variables.
If you want this happen on output then
you can use setprecision () method as it sets the decimal precision to be used to format floating-point values on output operations.
find more https://www.cplusplus.com/reference/iomanip/setprecision/#:~:text=std%3A%3Asetprecision&text=Sets%20the%20decimal%20precision%20to,input%20streams%20or%20output%20streams).
and check this solution for the problem
https://www.geeksforgeeks.org/rounding-floating-point-number-two-decimal-places-c-c/

C++ calculating more precise than double or long double

I'm teaching myself C++ and on this practice question it asks to write code that can calculate PI to >30 digits. I learned that double / long double are both 16 digits precise on my computer.
I think the lesson of this question is to be able to calculate precision beyond what is available. Therefore how do I do this? Is it possible?
my code for calculating Pi right now is
#include "stdafx.h"
#include <iostream>
#include <math.h>
#include <iomanip>
using namespace std;
int main(){
double pi;
pi = 4*atan(1.0);
cout<<setprecision(30)<<pi;
return 0;
}
Output is to 16 digits and pi to 30 digits is listed below for comparison.
3.1415926535897931
3.141592653589793238462643383279
Any suggestions for increasing precision or is this something that won't matter ever? Alternatively if there is another lesson you think I should be learning here feel free to offer it. Thank you!
You will need to perform the calculation using some other method than floating point. There are libraries for doing "long math" such as GMP.
If that's not what you're looking for, you can also write code to do this yourself. The simplest way is to just use a string, and store a digit per character. Do the math just like you would do if you did it by hand on paper. Adding numbers together is relatively easy, so is subtracting. Doing multiplication and division is a little harder.
For non-integer numbers, you'll need to make sure you line up the decimal point for add/subtract...
It's a good learning experience to write that, but don't expect it to be something you knock up in half an hour without much thought [add and subtract, perhaps!]
You can use quad math, builtin type __float128 and q/Q suffixes in GCC/clang.
#include <stdio.h>
#include <quadmath.h>
int main ()
{
__float128 x = strtoflt128("1234567891234567891234567891234566", nullptr);
auto y = 1.0q;
printf("%.Qf", x + y); // there is quadmath_snprintf, but this also works fine
return 0;
}

Using a long double or just a double for calculating pi?

I'm calculating pi using a long winded formula. I'm trying to get more familiar with floating point numbers etc. I have a working program that uses doubles. The problem with my code is:
If I use a double, pi is only accurate to the 7th decimal place. I can't get it to be any more accurate.
If I use a long double, pi is accurate up to the 9th decimal place however the code takes much longer to run. If I check for precision for less than 0.00000001 using a long double, pi returns a value of 9.4246775. I assume that this is due to the long double.
My question is what is the most accurate variable type? How could I change my code to improve the precision of pi?
Here is my code:
#include <iomanip>
#include <cstdlib>
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double arctan;
double pi;
double precision;
double previous=0;
int y=3;
int loopcount=0;
cout<<"Start\n";
arctan=1-(pow(1,y)/y);
do
{
y=y+2;
arctan=arctan+(pow(1,y)/y);
y=y+2;
arctan=arctan-(pow(1,y)/y);
pi=4*(arctan);
// cout<<"Pi is: ";
// cout<<setprecision(12)<<pi<<endl;
precision=(pi*(pow(10,10)/10));
loopcount++;
if(precision-previous<0.000000001)
break;
previous=precision;
}
while(true);
cout<<"Pi is:"<<endl;
cout<<setprecision(11)<<pi<<endl;
cout<<"Times looped:"<<endl;
cout<<loopcount<<endl;
return 0;
}
You can get the max limits of doubles/long doubles from std::numeric_limits
#include <iostream>
#include <limits>
int main()
{
std::cout << " Double::digits10: " << std::numeric_limits<double>::digits10 << "\n";
std::cout << "Long Double::digits10: " << std::numeric_limits<long double>::digits10 << "\n";
}
On my machine this gives:
Double::digits10: 15
Long Double::digits10: 18
So I expect long double to be accurate to 18 digits.
The definition of this term can be found here:
http://www.cplusplus.com/reference/std/limits/numeric_limits/
Standard quote: 18.3.2 Numeric limits [limits]
Also Note: As the comment is way down in the above list:
That #sarnold is incorrect (though mysteriously he has two silly people up-voting his comment without checking) in his assertions on pow(). What he states is only applicable to C. C++ has overloads for the types because in C++ pow() is a template function. See: http://www.cplusplus.com/reference/clibrary/cmath/pow/ in the standard at 26.4.7 complex value operations [complex.value.ops]
The predefined floating-point type with the greatest precision is long double.
There are three predefined floating-point types:
float has at least 6 decimal digits of precision
double has at least 10, and at least as many as float
long double has at least 10, and at least as many as double
These are minimum requirements; any or all of these types could have more precision.
If you need more precision than long double can provide, you might look at GMP, which supports arbitrary precision (at considerable expense in speed and memory usage).
Or, you could just hard-code the digits of PI and see what happens. ^_^
http://www.joyofpi.com/pi.html

Division in C++ not working as expected

I was working on something else, but everything came out as zero, so I made this minimalistic example, and the output is still 0.
#include <iostream>
int main(int argc, char** argv)
{
double f=3/5;
std::cout << f;
return 0;
}
What am I missing?
You are missing the fact that 3 and 5 are integers, so you are getting integer division. To make the compiler perform floating point division, make one of them a real number:
double f = 3.0 / 5;
It doesn't need to be .0, you can also do 3./5 or 3/5. or 3e+0 / 5 or 3 / 5e-0 or 0xCp-2 / 5 or... There only needs to be an indicator involved so that the compiler knows it's supposed to perform the division as floating point.
Another possibility: double f=double(3)/5. That's much more typing, but it leaves no doubt to what you are doing.
Or simply use double f=.6, that also does the trick...
try this:
double f = 3.0/5.0;
this should fix your problem
Try putting a .0 after one of the divisors. This will convert them into floating point literals.
You are using integers. You can many things to make your constants double like leftaroundabout states, however that is not good clean good. It is hard to read and confusing. If you want 3 and 5 make them 3.0 and 5.0. Everyone will know what you mean if they are forced to read your code. Much of what he/she states really requires you to know C/C++ and how floats are storage to make heads or tails.
In case, you save your generic variables with int and would like to obtain the ratio as double:
using namespace std;
int main()
{
int x = 7;
int y = 4;
double ratio;
ratio = static_cast<double>(x)/static_cast<double>(y);
cout << "ratio =\t"<<ratio<< endl;
}

decimal places and Pow function in c++

Most likely a really simple question, please keep any answers easy to understand I'm still quite new at this:
I'm making a little app, and I need to use powers for a couple of calculations. After a little research I found the pow function in cmath, and have had a play. In the end i came up with this snipped, which works:
#include <iostream>
#include <cmath>
using namespace std;
int main ()
{
float dummy2, test(6.65);
dummy2 = (float) pow((float) 3.57, test);
cout << dummy2;
return 0;
}
and it returns the correct answer (4734.17), but only to two decimal places. I want 5 decimal places preferably.
What did I do wrong here? Am I using the wrong data type (floats)? Or is it a limit of whatever is in the pow function to using only 2dp?
I could, if it came to it just define constants with the values i want, since it's only going to be 4 or 5 sums that I need this precision on, but if it's possible to have the program calculate it that would be great.
Thanks
I would do as fbinder says, and use Doubles for greater precision.
To solve your problem, you have two options, C-style and C++ style.
C-Style
#include <cstdio>
printf("%.5f", dummy2);
C++ Style
#include <iomanip>
std::cout << setprecision(5) << dummy2 << std::endl;
OR
std::cout.precision(5);
std::cout << dummy2 << std::endl;
// continue to use cout to output 5 decimal places
For a better precision you should use double. Doubles has 15 digits of precision against 7 for floats.